当前位置: 首页 > article >正文

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

http://www.kler.cn/a/382971.html

相关文章:

  • 前端:改变鼠标点击物体的颜色
  • 19_HTML5 Web Workers --[HTML5 API 学习之旅]
  • 探索Flink动态CEP:杭州银行的实战案例
  • 实战分享:开发设计文档模版及编写要点
  • 微信小程序 不同角色进入不同页面、呈现不同底部导航栏
  • Playwright爬虫xpath获取技巧
  • Nginx转发MySQL端口及添加stream模块
  • group by 聚合操作出错解决办法
  • 华为机试HJ25 数据分类处理
  • WPF MVVM入门系列教程(二、依赖属性)
  • 自注意力(Self-attention)与卷积神经网络(CNN)的相似性和区别
  • 如何在算家云搭建Aatrox-Bert-VITS2(音频生成)
  • 【python】OpenCV—findContours(4.6)
  • vue cli源码学习之cli-service
  • C语言算法编译成汇编语言增加保密性
  • Unity SRP学习笔记(二)
  • 语音识别中的RPM技术:原理、应用与发展趋势
  • java list使用基本操作
  • ReactPress系列—NestJS 服务端开发流程简介
  • 2024年世界职业院校技能大赛大数据应用与服务赛项(中职组)圆满闭幕
  • 复合查询【MySQL】
  • http 从请求到响应的过程中发生了什么
  • AI技术:转变未来生活与工作的革命性力量
  • 软件测试基础十二(python变量进阶)
  • 多模态大模型架构演变:主流模式的进化路径
  • Django+DRF+Celery+Redis通用Requirements记录