前面已经介绍了redux
的用法,但是在实际项目中,还是不够用的,不仅写法操作比较繁琐,而且实现的功能还有限,这篇我们引入官方推荐的react-redux
来简化我们的代码
实现效果
代码改造
- 安装相关依赖
npm i react-redux
store.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改写
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
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
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
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
方法可以去官网参考它对不同类型的数据操作使用
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » react18中引入redux及react-redux来管理公共数据仓库
发表评论 取消回复