Redux 仅支持同步数据流。使用 thunk 等中间件可以帮助在 Redux 应用中实现异步性。可以将 thunk 看做 store 的 dispatch() 方法的封装器;我们可以使用 thunk action creator 派遣函数或 Promise,而不是返回 action 对象。

设置用于异步的数据源

../public/data.json

  1. [
  2. "异步数据",
  3. "0"
  4. ]

抽离 store

创建 store/store.js

  1. import math from "../reducers/math";
  2. import { createStore } from "redux";
  3. const store = createStore(math, applyMiddleware(thunk));
  4. export default store;

引入 thunk

thunk 会以中间件的方式引入的,借助 redux 的 applyMiddleware 方法。

  1. import math from "../reducers/math";
  2. import { createStore, applyMiddleware } from "redux";
  3. import thunk from "redux-thunk";
  4. const store = createStore(math, applyMiddleware(thunk));
  5. export default store;

增加 get数据

componets/Container

  1. import React from "react";
  2. import { connect } from "react-redux";
  3. import { addAction, squareAction, getAction } from "../actions/actions";
  4. const mapStateToProps = (state) => {
  5. return {
  6. num: state,
  7. };
  8. };
  9. const mapDispatchToProps = (dispatch) => {
  10. return {
  11. add: (value) => dispatch(addAction(value)),
  12. square: () => dispatch(squareAction()),
  13. get: () => dispatch(getAction()),
  14. };
  15. };
  16. export default connect(
  17. mapStateToProps,
  18. mapDispatchToProps
  19. )(function Container(props) {
  20. const { num, add, square, get } = props;
  21. return (
  22. <div>
  23. <p>{num}</p>
  24. <button onClick={() => add(1)}>加1</button>
  25. <button onClick={() => add(2)}>加2</button>
  26. <button onClick={() => square()}>乘方</button>
  27. <button onClick={() => get()}>get数据</button>
  28. </div>
  29. );
  30. });

constans/ActionTypes.js

  1. export const ADD = "ADD";
  2. export const SQUARE = "SQUARE";
  3. export const GET = "GET";

reducers/math.js 处理 GET 的 action

  1. import { ADD, SQUARE, GET } from "../constans/ActionTypes";
  2. export default (state = 10, action) => {
  3. switch (action.type) {
  4. case ADD:
  5. return state + action.num;
  6. case SQUARE:
  7. return state ** 2;
  8. case GET:
  9. return action.num;
  10. default:
  11. return state;
  12. }
  13. };

使用 fetch API 来异步获取数据
actions/actions.js

  1. import { ADD, SQUARE,GET } from "../constans/ActionTypes";
  2. export const addAction = (num) => {
  3. return {
  4. type: ADD,
  5. num,
  6. };
  7. };
  8. export const squareAction = () => {
  9. return {
  10. type: SQUARE,
  11. };
  12. };
  13. export const getAction = () => {
  14. return (dispatch, getState) => { // 如果 action 是一个函数是,会先执行函数,再以函数的返回值来返回。
  15. fetch("./data.json")
  16. .then((res) => res.json())
  17. .then((json) =>
  18. dispatch({
  19. type: "GET",
  20. num: Number(json[1]),
  21. })
  22. );
  23. };
  24. };