当前位置: 首页 > news >正文

React 状态管理(手写实现react-redux)

什么是状态管理:
状态管理就是管理应用程序中会变化的数据的一套方法或工具
在react下实现一套状态管理

  1. 组件之外可以共享数据状态
  2. 数据更新,会触发相关方法
  3. 数据更新触发ui更新
    以这几点我们可以基于React框架实现一套自己的状态管理工具
//store.ts
interface Action {type: string,payload?:any
}
const creatData = function (init: any) {let data = init; //初始化数据let deps:Array<Function> = []; //需要订阅的方法function subscribe(fn:Function) {//开始订阅deps.push(fn)return () => {  //取消订阅let index = deps.indexOf(fn);deps.splice(index,1)}}function setDataByAction(action: Action) {const currentData = reducer(data,action) //通过reducer 方法更新状态data = currentData;deps.forEach(fn => fn()) //通知所有订阅者} function getData() {return data}return {subscribe,setDataByAction,getData}
}
const init = {count: 0
}
const reducer = (data:any, action:Action) => {switch(action.type) {case 'add_count':return {count: data.count + 1}case 'change_count':return {count : action.payload}default:return data;}
}
export const objData = creatData(init);

消费阶段

import { objData } from "./store";
const addAction = {type: 'add_count',
}
const changeAction = {type: 'change_count',payload: 100
}
const Button1 = () => {const handleAdd = () => {objData.setDataByAction(addAction)}return <button onClick={handleAdd}></button>;
};
const Button2 = () => {const handleChange = () => {objData.setDataByAction(changeAction)}return <button onClick={handleChange}>修改</button>;
};
const App = () => {const [count, setCount] = useState<number>(0);useEffect(() => {objData.subscribe(() => { //添加监听方法 触发ui更新let data = objData.getData();setCount(data.count);});}, []);return (<div><div>当前数字状态:{count}</div><Button1></Button1><Button2></Button2></div>);
};

这里基本实现了状态管理,其实这也是redux的实现原理,我们继续完善,现在的如果所有的Action全都由同一个reducer方法去管理,基于性能以及可维护性都不好,接下来实现合并reducer

const init = {counter: {count: 0,},info: {name: '张三',age: 16}
}
const counterReducer = (data: any, action: Action) => {console.log(data,action)switch (action.type) {case 'add_count':return { count: data.count + 1 } case 'change_count':return  { count: action.payload } default:return data;}
}
const infoReducer = (data: any, action: Action) => {switch (action.type) {case 'change_age':return  { name: action.payload } case 'change_person':return  { ...action.payload } default:return data;}
}
interface Reducers {counter: Function,info: Function,[key:string]: Function,
}
const combineReducer = function (reducers:Reducers) {return (data: any, action: Action) => { //返回合并后的reducer函数let keys = Object.keys(reducers)const nextState = {} as Reducers; //定义变量存储处理后的datakeys.forEach(key => { //循环执行所有的reducer 合并值let reducerAction = reducers[key]; let cur_state = data[key];const next = reducerAction(cur_state, action)nextState[key] = next})return nextState}
}
const reducer = combineReducer({counter: counterReducer,info: infoReducer
})

这个时候虽然也实现了合并,但是数据的更新我们需要大量的订阅函数以及useState定义,模仿react-redux 结合context实现子组件自动更新

//app.tsx
import myStore from "./store";
const ReduxContext = createContext<null | any>({});
const connect =(mapStateToProps: Function, mapDispatchToProps: Function) =><P extends object>(MyComponent) => {return function ConnectComponent(props: P) {const _store = useContext(ReduxContext);const foceUpdate = () => {setBool(pre => !pre);};useEffect(() => {const unsubscribe = _store.subscribe(() => foceUpdate()); //监听函数,store数据变动强制触发消费store的组件进行更新return () => { //React.StrictMode 模式下必须添加清理函数,否则组件不会触发更新unsubscribe();};}, []);const [, setBool] = useState(false);return (<ReduxContext.Consumer>{store => (<MyComponent{...mapDispatchToProps(store.setDataByAction)}{...mapStateToProps(store.getData())}{...props}/>)}</ReduxContext.Consumer>);};};
const ConnectTest = ({ counter, handleAdd }) => {return (<div><div>当前数字: {counter.count}</div><button onClick={() => handleAdd()}>添加</button></div>);
};
const mapStateToProps = state => {return { counter: state.counter };
};
const mapDispatchToProps = dispatch => {return {handleAdd: () => {console.log("触发更新");dispatch({ type: "add_count" });},};
};
const ConnectCom = connect(mapStateToProps, mapDispatchToProps)(ConnectTest);
const App = () => {return (<ReduxContext.Provider value={myStore}><ConnectCom></ConnectCom></ReduxContext.Provider>);
};

文章转载自:

http://tt6bkR6E.kjfsd.cn
http://Gogdlduj.kjfsd.cn
http://nmrmLAww.kjfsd.cn
http://93L5NzpP.kjfsd.cn
http://5Jetna1G.kjfsd.cn
http://KgXzmbOy.kjfsd.cn
http://JQykno4j.kjfsd.cn
http://hs2pMfLd.kjfsd.cn
http://KQ7ILOKf.kjfsd.cn
http://kpQv14ln.kjfsd.cn
http://c6SelswT.kjfsd.cn
http://nYkIx0PQ.kjfsd.cn
http://ByEbciw2.kjfsd.cn
http://PgTcHoLm.kjfsd.cn
http://rIX3jprE.kjfsd.cn
http://XklC4LxX.kjfsd.cn
http://L3xsyC1j.kjfsd.cn
http://nY4EVtag.kjfsd.cn
http://eTpt6qnV.kjfsd.cn
http://cwwUjJkb.kjfsd.cn
http://3s4EpQB6.kjfsd.cn
http://B6pJeBiV.kjfsd.cn
http://Wpvmd4nM.kjfsd.cn
http://GZwzDfC1.kjfsd.cn
http://9W609ieH.kjfsd.cn
http://Shi4Ct51.kjfsd.cn
http://MmBbUEth.kjfsd.cn
http://B3Jdys3Q.kjfsd.cn
http://SAbzfGHN.kjfsd.cn
http://fz2pCsje.kjfsd.cn
http://www.dtcms.com/a/384110.html

相关文章:

  • C++:类和对象(下)
  • 智能驾驶再加速:L4 级 AI 系统落地难点与城市试点经验总结
  • 第4章:CPU进阶命令
  • brew@homebrew@linux通用包管理工具linuxbrew
  • NumPy 是 Python 科学计算的基石
  • LLMs之RL之GRPO:《Magistral》的翻译与解读
  • FPGA入门-数码管静态显示
  • 【大模型】企业级应用场景概览
  • uTools 轻工具 简洁又方便
  • Can总线原理
  • Matplotlib 全面详解:从入门到高级应用
  • 爬虫获取API接口的实战指南
  • 裸机开发 时钟配置,EPIT
  • TypeScript项目中,ESLint配置支持子路径的模块导入
  • 机器视觉中的工业相机接口该如何选择?
  • Knockout.js DOM 节点清理模块详解
  • 基于Python的个性化书籍推荐管理系统【2026最新】
  • Java Collection集合框架:体系、核心与选型
  • 最长递减子序列 动态规划
  • C# --- Field and Property
  • 一次 界面无法启动的问题 的解决记录
  • 011=基于YOLO12电动车进电梯检测与警告系统(Python+PySide6界面+训练代码)
  • Antminer S19 Pro 92T矿机详细参数解析与挖矿能力分析
  • LChot100--1143. 最长公共子序列
  • Android开发-选择按钮
  • [温习C/C++]0x06 坐标系中矩形重叠类问题分析
  • 拓扑排序应用——火星词典
  • Afsim沿高程运动
  • PADS查看板子Pins数
  • Photoshop - Photoshop 创建照片晕影