Redux 仅支持同步数据流。使用 thunk 等中间件可以帮助在 Redux 应用中实现异步性。可以将 thunk 看做 store 的 dispatch() 方法的封装器;我们可以使用 thunk action creator 派遣函数或 Promise,而不是返回 action 对象。
设置用于异步的数据源
../public/data.json
["异步数据","0"]
抽离 store
创建 store/store.js
import math from "../reducers/math";import { createStore } from "redux";const store = createStore(math, applyMiddleware(thunk));export default store;
引入 thunk
thunk 会以中间件的方式引入的,借助 redux 的 applyMiddleware 方法。
import math from "../reducers/math";import { createStore, applyMiddleware } from "redux";import thunk from "redux-thunk";const store = createStore(math, applyMiddleware(thunk));export default store;
增加 get数据
componets/Container
import React from "react";import { connect } from "react-redux";import { addAction, squareAction, getAction } from "../actions/actions";const mapStateToProps = (state) => {return {num: state,};};const mapDispatchToProps = (dispatch) => {return {add: (value) => dispatch(addAction(value)),square: () => dispatch(squareAction()),get: () => dispatch(getAction()),};};export default connect(mapStateToProps,mapDispatchToProps)(function Container(props) {const { num, add, square, get } = props;return (<div><p>{num}</p><button onClick={() => add(1)}>加1</button><button onClick={() => add(2)}>加2</button><button onClick={() => square()}>乘方</button><button onClick={() => get()}>get数据</button></div>);});
constans/ActionTypes.js
export const ADD = "ADD";export const SQUARE = "SQUARE";export const GET = "GET";
reducers/math.js 处理 GET 的 action
import { ADD, SQUARE, GET } from "../constans/ActionTypes";export default (state = 10, action) => {switch (action.type) {case ADD:return state + action.num;case SQUARE:return state ** 2;case GET:return action.num;default:return state;}};
使用 fetch API 来异步获取数据
actions/actions.js
import { ADD, SQUARE,GET } from "../constans/ActionTypes";export const addAction = (num) => {return {type: ADD,num,};};export const squareAction = () => {return {type: SQUARE,};};export const getAction = () => {return (dispatch, getState) => { // 如果 action 是一个函数是,会先执行函数,再以函数的返回值来返回。fetch("./data.json").then((res) => res.json()).then((json) =>dispatch({type: "GET",num: Number(json[1]),}));};};
