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中
相关推荐
Σίσυφος19001 小时前
halcon 条形码、二维码识别、opencv识别
前端·数据库
学代码的小前端1 小时前
0基础学前端-----CSS DAY13
前端·css
css趣多多3 小时前
案例自定义tabBar
前端
姑苏洛言4 小时前
DeepSeek写微信转盘小程序需求文档,这不比产品经理强?
前端
林的快手4 小时前
CSS列表属性
前端·javascript·css·ajax·firefox·html5·safari
匹马夕阳5 小时前
ECharts极简入门
前端·信息可视化·echarts
API_technology5 小时前
电商API安全防护:JWT令牌与XSS防御实战
前端·安全·xss
yqcoder5 小时前
Express + MongoDB 实现在筛选时间段中用户名的模糊查询
java·前端·javascript
十八朵郁金香5 小时前
通俗易懂的DOM1级标准介绍
开发语言·前端·javascript
m0_528723816 小时前
HTML中,title和h1标签的区别是什么?
前端·html