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

react18中react-thunk实现公共数据仓库的异步操作

reduxreact-redux都只能实现数据的同步修改更新,有点类似于vue中的mutation,只能做同步操作,异步的话不用actions来实现。由于在项目始终不可避免要实现的异步数据的更新,这明显不够用了。是时候引入我们的异步中间件redux-thunk

实现效果

请添加图片描述

代码实现

  • 安装redux-thunk
npm i redux-thunk
  • store/index.js
import { createStore, applyMiddleware, compose } from "redux";
import { combineReducers } from "redux-immutable";
import { thunk } from "redux-thunk";import { CounterReducer } from "./CounterReducer";const reducers = combineReducers({count: CounterReducer,
});
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;const store = createStore(reducers, composeEnhancers(applyMiddleware(thunk)));export default store;
  • CounterReducer.js
    封装了两个异步方法,模拟数据的异步获取,然后导出供其他组件使用
import { fromJS } from "immutable";
const initialState = fromJS({counter: 0,userInfo: {name: "John Doe",age: 25,},
});
function CounterReducer(state = initialState, action) {console.log("🚀 ~ CounterReducer ~ action:", action);switch (action.type) {case "ADD":return state.update("counter", (val) => {return val + 1;});case "ADD_TWO":return state.update("counter", (val) => {return val + 2;});case "DEC":return state.update("counter", (val) => val - 1);case "DEC_TWO":return state.update("counter", (val) => val - 2);case "CHANGE_NAME":return state.setIn(["userInfo", "name"], action.payload);default:return state;}
}// async action 2s later
function handleDelayAdd() {return (dispatch) => {// 模拟异步接口setTimeout(() => dispatch({ type: "ADD_TWO" }), 2000);};
}// async action 2s later
function handleDelayReduce() {return (dispatch) => {// 模拟异步接口setTimeout(() => dispatch({ type: "DEC_TWO" }), 2000);};
}export { CounterReducer, handleDelayAdd, handleDelayReduce };
  • DemoB.js
    引入两个异步的方法,注意跟同步的dispatch使用方法有点区别,dispatch(handleDelayAdd())dispatch直接调用了该方法
import { useSelector, useDispatch } from "react-redux";
import { Button, Space, Divider } from "antd";
import { handleDelayAdd, handleDelayReduce } from "../../store/CounterReducer";
function DemoB() {const count = useSelector((state) => state.getIn(["count", "counter"]));const userInfo = useSelector((state) => state.getIn(["count", "userInfo"]));const dispatch = useDispatch();return (<div><p>Demo B</p><div><Space split={<Divider />}><span>name: {userInfo.get("name")}</span><span>age: {userInfo.get("age")}</span><span>count:{count}</span></Space></div><Space><Button type="primary" onClick={() => dispatch({ type: "ADD" })}>add count</Button><Button type="primary" danger onClick={() => dispatch({ type: "DEC" })}>minus count</Button><Button type="primary" onClick={() => dispatch(handleDelayAdd())}>delay 2s add count</Button><Buttontype="primary"dangeronClick={() => dispatch(handleDelayReduce())}>delay 2s minus count</Button><Buttontype="dashed"dangeronClick={() => dispatch({ type: "CHANGE_NAME", payload: "张学友" })}>change name</Button></Space></div>);
}
export default DemoB;

这样我们就实现了在react项目中数据的异步更新。整体还是比较简单的。

总结

在这个具有副作用的action中,我们可以看出,函数内部可能极为复杂。如果需要为每一个异步操作都如此定义一个action,显然action不易维护。

action不易维护的原因:

  • action的形式不统一
  • 就是异步操作太为分散,分散在了各个action中

http://www.mrgr.cn/news/60453.html

相关文章:

  • 【C++】继承与模板
  • Mysql之视图创建
  • django5入门【04】Django框架配置文件说明:settings.py
  • git命令报错:fatal: not a git repository (or any of the parent directories): .git
  • PHP程序开发基础
  • 颠覆级AI:10秒生成超清视频
  • WSGI、uwsgi与uWSGI
  • [ComfyUI]Mochi:最强视频开源模型,它来了!
  • 使用libimobiledevice+ifuse访问iOS沙盒目录
  • Python(pandas库3)
  • C# 结构型设计模式----适配器模式
  • ShellScript脚本编程1_(介绍与变量篇)
  • 验证俩套加密算法是否互通
  • Apache paimon 优化
  • 【题解】【分治】——黑白棋子的移动
  • Pytorch学习--如何下载及使用Pytorch中自带数据集,如何把数据集和transforms联合在一起使用
  • 【亲测】mini版centos7.9配置网络基础ssh等直接使用
  • Linux端使用百度网盘命令行工具深度指南
  • 运维工程师面试题
  • 《证据规定》之关于鉴定人出庭的操作性规定
  • 一篇教你“uniapp小程序 app新用户引导实现”
  • 使用 LiteLLM 或 Qwen 等 LLM API 替代 OpenAI(Swarm 中应用)
  • Spring 设计模式之工厂模式
  • HelloCTF [RCE-labs] Level 4 - SHELL 运算符
  • php字符过滤绕过方法
  • 越南有哪些主要的电商平台?越南电商什么品类比较畅销?