react18中引入redux及react-redux来管理公共数据仓库

前面已经介绍了redux的用法,但是在实际项目中,还是不够用的,不仅写法操作比较繁琐,而且实现的功能还有限,这篇我们引入官方推荐的react-redux来简化我们的代码

实现效果

代码改造

  • 安装相关依赖
bash 复制代码
npm i react-redux

store.js改写

js 复制代码
import { createStore } from "redux";
import { combineReducers } from "redux-immutable";

import { CounterReducer } from "./CounterReducer";

const reducers = combineReducers({
  count: CounterReducer,
});

const store = createStore(reducers);

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 "DEC":
      return state.update("counter", (val) => val - 1);
    case "CHANGE_NAME":
      return state.setIn(["userInfo", "name"], action.payload);
    default:
      return state;
  }
}

export { CounterReducer };

DemoA.js

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

function DemoA() {
  const count = useSelector((state) => state.getIn(["count", "counter"]));
  return (
    <div>
      <p> Demo A count: {count}</p>
    </div>
  );
}
export default DemoA;

DemoB.js

js 复制代码
import { useSelector, useDispatch } from "react-redux";
import { Button, Space, Divider } from "antd";
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="dashed"
          danger
          onClick={() => dispatch({ type: "CHANGE_NAME", payload: "张学友" })}
        >
          change name
        </Button>
      </Space>
    </div>
  );
}
export default DemoB;

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 counter = useSelector((state) => state.getIn(["count", "counter"]));
  return (
    <div>
      Redux parent count:{counter}
      <Divider />
      <Space split={<Divider type="vertical" />}>
        <DemoA />
        <DemoB />
      </Space>
    </div>
  );
}

export default Redux;

引入了react-redux后的,代码的确是清爽了很多,没有之前的臃肿了。

总结

  • useSelector获取store中的数据
  • useDispatch触发reducer中的方法
  • immutable中fromJS方法可以去官网参考它对不同类型的数据操作使用
相关推荐
拖孩14 分钟前
# 我又用 AI 做了个小程序:24 天,记录我这辈子认识的人
前端·后端·微信小程序
徐小夕23 分钟前
深度拆解 Design Agent:LangChain 出品,AI 设计从「好看」走向「可用」
前端·vue.js·github
1-1=01 小时前
Vue 表单数据和过滤器
前端·javascript·vue.js
oil欧哟1 小时前
Oil UI 的设计思路与日常使用方式:让 AI 摆脱默认模板并保持多页面风格统一
前端
恋猫de小郭1 小时前
Jetpack Compose 1.13 发布,憋了这么久终有交代了
android·前端·flutter
头发还在的女程序员2 小时前
智慧物业源码解析:房屋档案与业主变更怎样保持历史业务连续
前端·javascript·vue.js·物业管理·小区物业·智慧物业
JianZhen✓2 小时前
电商 SKU 选择器:后端只给扁平列表,前端怎么反推规格矩阵并做到 O(1) 命中
前端·矩阵·状态模式
feixing_fx10 小时前
第一个 JS 程序:在浏览器控制台和 Node 中分别运行
开发语言·前端·javascript·前端框架·ecmascript
feixing_fx12 小时前
变量与声明:let、const、var 的选择边界
开发语言·前端·javascript·前端框架
JavaGuide14 小时前
Cloudflare 开源的这套神级安全审计 Skill 太好用了!
前端·后端