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

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

实现效果

关键逻辑代码

  • store/index.js
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
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中间件的配置好后,页面会立马报错。

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 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;
  • 组件代码
js 复制代码
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;

参考资料

相关推荐
木子七6 分钟前
Js Dom
前端·javascript
谢小飞38 分钟前
我做了三把椅子原来纹理这样加载切换
前端·three.js
圈圈的熊38 分钟前
HTTP 和 HTTPS 的区别
前端·网络协议·http·https
GIS程序媛—椰子1 小时前
【Vue 全家桶】2、Vue 组件化编程
前端·javascript·vue.js
Beamon__1 小时前
element-plus按需引入报错IconsResolver is not a function
前端
努力奔波的程序猿1 小时前
HBuilderx修改主题色-改变编辑器背景颜色等
前端
正小安1 小时前
Vue 3 性能提升与 Vue 2 的比较 - 2024最新版前端秋招面试短期突击面试题【100道】
前端·vue.js·面试
yqcoder1 小时前
electron 中 ipcRenderer 的常用方法有哪些?
前端·javascript·electron
用户8185216881171 小时前
react项目搭建create-router-dom,redux详细解说
react.js