react18中redux-promise搭配redux-thunk完美简化异步数据操作

用过redux-thunk的应该知道,操作相对繁琐一点,dispatch本只可以出发plain objectredux-thunkdispatch可以返回一个函数。而redux-promise在此基础上大大简化了操作。

实现效果

请添加图片描述

关键逻辑代码

  • store/index.js
import { createStore, applyMiddleware } from "redux";
import { combineReducers } from "redux-immutable";
import { thunk } from "redux-thunk";
import { createLogger } from "redux-logger";
import reduxPromise from "redux-promise";
import reducer from "./reducer";

const middleware = [thunk, reduxPromise];
const env = process.env.NODE_ENV;
if (env === "development") {
  middleware.push(createLogger({ collapsed: true }));
}

const store = createStore(reducer, applyMiddleware(...middleware));

export default store;
  • reucer.js
import { fromJS } from "immutable";
import { delay } from "../../utils";
const initstate = fromJS({
  list: [],
  count: 100,
});

function storeReducers(state = initstate, action) {
  console.log("???? ~ storeReducers ~ action:", action);
  switch (action.type) {
    case "ADD":
      return state.updateIn(["count"], (n) => n + action.value);
    case "MINUS":
      return state.updateIn(["count"], (n) => n - action.value);
    default:
      return state;
  }
}

export async function handleAdd() {
  await delay(2000);
  const data = await Promise.resolve(20);
  return { type: "ADD", value: data };
}

export async function handleMinus() {
  await delay(2000);
  const data = await Promise.resolve(20);
  return { type: "MINUS", value: data };
}

export default storeReducers;

可以发现在handleAdd里面写异步业务获取返回数据是可以正常执行的,功能完好。

当我们注释掉redux-promise中间件的配置好后,页面会立马报错。

import { createStore, applyMiddleware } from "redux";
import { combineReducers } from "redux-immutable";
import { thunk } from "redux-thunk";
import { createLogger } from "redux-logger";
// import reduxPromise from "redux-promise";
import reducer from "./reducer";

// const middleware = [thunk, reduxPromise];
const middleware = [thunk];
const env = process.env.NODE_ENV;
if (env === "development") {
  middleware.push(createLogger({ collapsed: true }));
}

const store = createStore(reducer, applyMiddleware(...middleware));
export default store;

在这里插入图片描述

  • 组件代码
import { Button, Dialog, setDefaultConfig, Space, Toast } from "antd-mobile";
import { http } from "../api/request";
import { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { handleAdd, handleMinus } from "../store/reducer/store";
function Home() {
  const count = useSelector((state) => state.getIn(["store", "count"]));
  const dispatch = useDispatch();
  function handleAddCount() {
    dispatch(handleAdd());
  }
  function handleMinusCount() {
    dispatch(handleMinus());
  }
  return (
    <div className="home-box">
      <h2>home</h2>
      <p>{count}</p>
      <Space>
        <Button color="primary" onClick={handleAddCount}>
          add
        </Button>
        <Button color="danger" onClick={handleMinusCount}>
          minus
        </Button>
      </Space>
    </div>
  );
}
export default Home;

参考资料

  • https://github.com/redux-utilities/redux-promise
上一篇:Git (推送到远端仓库)


下一篇:一 Spring6启示录