react18中Redux Toolkit进一步排除公共数据仓库使用的心智成本

Redux Toolkit的出现,让我们进一步释放双手,越来越简单啦!!如果你觉得redux-thunk不好用的话,官方又给我们推出了一套的新的方案:redux-toolkit,当你用完后,你会发现,和vue3的pinia是多么的相似!!!

redux-toolkit 内部帮我们做了很多内置工作,让我们可以直接修改state,不再需要redux-immutable和mmutable,使我们能方便的处理数据了。

实现效果

代码实现

  • 安装
bash 复制代码
npm i redux-toolkit
  • store/index.js
js 复制代码
import { configureStore } from "@reduxjs/toolkit";
import CounterReducer from "./CounterReducer";

export const store = configureStore({
  reducer: {
    count: CounterReducer,
    // other reducers
  },
});

export default store;
  • CounterReducer.js
js 复制代码
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
  counter: 0,
  userInfo: {
    name: "John Doe",
    age: 25,
  },
};
export const counterSlice = createSlice({
  name: "counter",
  initialState,
  reducers: {
    add: (state) => {
      state.counter += 1;
      console.log("🚀 ~ state:", state.counter);
    },
    dec: (state) => {
      state.counter -= 1;
      console.log("🚀 ~ state:", state.counter);
    },
    changeName: (state, action) => {
      console.log("🚀 ~ payload:", action);
      state.userInfo.name = action.payload;
    },
    handleDelayAddByTen1: (state, action) => {
      console.log("🚀 ~ action:", action);
      state.counter += action.payload;
    },
  },
});

// async action 2s later
function handleDelayAdd() {
  return (dispatch) => {
    setTimeout(() => dispatch(add()), 2000);
  };
}

// async action 2s later
function handleDelayReduce() {
  return (dispatch) => {
    setTimeout(() => dispatch(dec()), 2000);
  };
}

function handleDelayAddByTen(count) {
  return (dispatch) => {
    setTimeout(() => dispatch(handleDelayAddByTen1(count)), 2000);
  };
}

// export actions,提供给组件调用
export const { add, dec, changeName, handleDelayAddByTen1 } =
  counterSlice.actions;

export { handleDelayAdd, handleDelayReduce, handleDelayAddByTen };

// export reducer,提供给store使用
export default counterSlice.reducer;
  • DemoB.js
js 复制代码
import { useSelector, useDispatch } from "react-redux";
import { Button, Space, Divider } from "antd";
import {
  add,
  dec,
  changeName,
  handleDelayAdd,
  handleDelayReduce,
  handleDelayAddByTen,
} from "../../store/CounterReducer";
function DemoB() {
  const count = useSelector((state) => state.count.counter);
  const userInfo = useSelector((state) => state.count.userInfo);
  const dispatch = useDispatch();
  return (
    <div>
      <p>Demo B</p>
      <div>
        <Space split={<Divider />}>
          <span>name: {userInfo.name}</span>
          <span>age: {userInfo.age}</span>
          <span>count:{count}</span>
        </Space>
      </div>
      <Space>
        <Button type="primary" onClick={() => dispatch(add())}>
          add count
        </Button>
        <Button type="primary" danger onClick={() => dispatch(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="primary"
          onClick={() => dispatch(handleDelayAddByTen(10))}
        >
          delay 2s add count by 10
        </Button>
        <Button
          type="dashed"
          danger
          onClick={() => dispatch(changeName("张学友"))}
        >
          change name
        </Button>
      </Space>
    </div>
  );
}
export default DemoB;

-DemoA.js

js 复制代码
import { useSelector } from "react-redux";

function DemoA() {
  const count = useSelector((state) => state.count.counter);
  return <div>{<p> Demo A count: {count}</p>}</div>;
}
export default DemoA;
  • index.js
js 复制代码
import DemoA from "./DemoA";
import DemoB from "./DemoB";
import store from "../../store/index";
import { useEffect, useState } from "react";
import { Divider, Space } from "antd";
import { useSelector } from "react-redux";
function Redux() {
  const count = useSelector((state) => state.count.counter);
  return (
    <div>
      Redux parent count:{count}
      <Divider />
      <Space split={<Divider type="vertical" />}>
        <DemoA />
        <DemoB />
      </Space>
    </div>
  );
}

export default Redux;

总结

  • 这一套下来,简直不要太简单了,同步异步的操作与redux-thunk大同小异了,很容易理解。
  • 参考redux-toolkit官网地址
相关推荐
Dovis(誓平步青云)几秒前
切换语言后按钮被截断,本地化审计怎样发现长度风险
开发语言·前端·javascript·人工智能·机器学习·华为·harmonyos
CappuccinoRose7 分钟前
拖拽交互体系
前端·javascript·css·html·交互·1024程序员节
开开心心就好9 分钟前
免安装PDF盖章工具,透明度和位置可调
运维·服务器·前端·javascript·pdf·ocr·1024程序员节
风骏时光牛马9 分钟前
AI服务线上推理异常故障
前端
king王一帅21 分钟前
做了三年 ProseMirror 后,我用四个月自研排版引擎实现 WPS / Google Docs 替代品,整套框架 MIT 开源
前端·vue.js·开源
এ慕ོ冬℘゜2 小时前
如何在 HTML 中嵌入音频和视频?
前端·html·音视频
变与不变80611 小时前
jQuery怎么使用
前端·javascript
神膘护体小月半11 小时前
flex 布局的 order 属性
前端·css
paopaokaka_luck11 小时前
流浪动物救助与收养系统(DeepSeek AI对话、 ECharts多维分析、救助流程衔接、领养与回访衔接、 捐赠确认与公示、志愿者协作)
java·前端·javascript·人工智能·mysql·echarts·推荐算法
仰望.11 小时前
vue 表格组件 vxe-table 树表格懒加载支持拖拽排序的详细用法
前端·javascript·vue.js·vxe-table