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;

参考资料

相关推荐
m0_7482552617 分钟前
easyExcel导出大数据量EXCEL文件,前端实现进度条或者遮罩层
前端·excel
web147862107231 小时前
C# .Net Web 路由相关配置
前端·c#·.net
m0_748247801 小时前
Flutter Intl包使用指南:实现国际化和本地化
前端·javascript·flutter
飞的肖1 小时前
前端使用 Element Plus架构vue3.0实现图片拖拉拽,后等比压缩,上传到Spring Boot后端
前端·spring boot·架构
青灯文案11 小时前
前端 HTTP 请求由 Nginx 反向代理和 API 网关到后端服务的流程
前端·nginx·http
m0_748254881 小时前
DataX3.0+DataX-Web部署分布式可视化ETL系统
前端·分布式·etl
用户30587584891251 小时前
Connected-react-router核心思路实现
react.js
ZJ_.1 小时前
WPSJS:让 WPS 办公与 JavaScript 完美联动
开发语言·前端·javascript·vscode·ecmascript·wps
GIS开发特训营1 小时前
Vue零基础教程|从前端框架到GIS开发系列课程(七)响应式系统介绍
前端·vue.js·前端框架·gis开发·webgis·三维gis
Cachel wood2 小时前
python round四舍五入和decimal库精确四舍五入
java·linux·前端·数据库·vue.js·python·前端框架