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

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

实现效果

代码实现

  • 安装redux-thunk
bash 复制代码
npm i redux-thunk
  • store/index.js
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
    封装了两个异步方法,模拟数据的异步获取,然后导出供其他组件使用
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直接调用了该方法
js 复制代码
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>
        <Button
          type="primary"
          danger
          onClick={() => dispatch(handleDelayReduce())}
        >
          delay 2s minus count
        </Button>
        <Button
          type="dashed"
          danger
          onClick={() => dispatch({ type: "CHANGE_NAME", payload: "张学友" })}
        >
          change name
        </Button>
      </Space>
    </div>
  );
}
export default DemoB;

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

总结

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

action不易维护的原因:

  • action的形式不统一
  • 就是异步操作太为分散,分散在了各个action中
相关推荐
梦曦i4 小时前
@meng-xi/create-uni-app vs unibest:轻量脚手架与重型框架的定位之争
前端·uni-app
平头哥技术团队4 小时前
Day 10 | 工欲善其事:VS Code 配置与项目归档
android·开发语言·前端·javascript·html·交互
乌恩大侠5 小时前
GH200 新增 NVMe SSD 分区、格式化与挂载完整流程
运维·服务器·前端
yume_sibai5 小时前
Element Plus 数据展示组件完全指南(15个核心组件)
前端·javascript·vue.js
qiuhaipeng15 小时前
Claude code 升级后上下文长度变短问题
java·前端·数据库
zzz_23686 小时前
个人 AI 记忆如何跨工具复用:用 Markdown、索引和 Skill 搭一个可治理的记忆库
前端·人工智能·react.js·前端框架·agent·agent测评
剑之所向7 小时前
.NET 官方`System.Threading.Channels`
前端·javascript·数据库
计算机魔术师8 小时前
GPT-6 Astra幻觉砍到2%,却被一种老招数轻松绕过
前端
cjy0001118 小时前
2026AI 产品如何从一次性 Demo 变成可重复使用的业务工具?
前端·人工智能·fde
IT_陈寒8 小时前
React的状态更新坑得我差点加班到天亮
前端·人工智能·后端