react,useReducer结合useContext跨组件状态管理终极版
发布于 作者:苏南大叔 来源:程序如此灵动~
react项目,其实就是调用各种函数修改各种数据。那么,useReducer是react官方推荐的useState的升级版,可以用于集中管理数据和修改数据的函数,而useContext又具有跨组件传递数据的能力。所以,本文讨论的话题依然是:useReducer结合useContext跨组件状态管理。本文为了解决层层传值的问题,抛弃props传值的方式,将数据包裹进context。

大家好,这里是苏南大叔的程序如此灵动博客,这里记录苏南大叔和计算机代码的故事。本文继续描述react项目的useReducer和useContext的跨组件状态管理的终极版。测试环境:create-react-app@5.0.1,node@16.14.2,react@18.2.0,react-dom@18.2.0。
基本内容
为了更好的理解本文的内容,推荐大家阅读一下本文的前置内容:
本文的代码和上一篇文章中的代码基本雷同,有区别的地方就是改进之处。主要的思路就是,把useReducer的的结果state和dispatch再进行从新进行组合,然后传入prodiver的value中。在各个被嵌套的组件中,可以通过useContext获得上述state和dispatch的组合。

定义context、reducer、prodiver
这里对做context和reducer基本定义,注意这里给context做了一个默认值,用于没有被prodiver包裹的情况(虽然可能性为零)。
import React, { useReducer, useContext } from 'react';
const sunanContext = React.createContext({
text: "",
sunanDispatch: () => { },
});
const sunanReducer = (state, action) => {
switch (action.type) {
case "add":
return { ...state, text: action.text }
default:
throw Error();
}
}
function SunanComponent() {
const [sunanState, sunanDispatch] = useReducer(sunanReducer, { text: "----" });
return (
<sunanContext.Provider value={{ ...sunanState, sunanDispatch }}>
<SunanOuter/>
</sunanContext.Provider>
);
}
export default SunanComponent;核心代码:
<xxxContext.Provider value={{ ...xxxState, xxxDispatch }}>
定义内部嵌套组件
function SunanInner() {
const ctx = useContext(sunanContext);
function handleClick() {
ctx.sunanDispatch({ type: 'add', text: '高兴' });
}
return (
<>
子组件接收状态:{ctx.text}
<button onClick={handleClick.bind()}>High起来</button>
<button onClick={() => { ctx.sunanDispatch({ type: 'add', text: '非常高兴' }); }}>
更加High起来</button>
</>
);
}
function SunanOuter() {
const ctx = useContext(sunanContext);
return <>
苏南大叔的心情:{ctx.text}<br /><br />
<SunanInner />
</>
}核心代码是:
const ctx = useContext(sunanContext);
ctx.sunanDispatch({ type: 'add' });
相关文章
- https://newsn.net/say/create-react-app.html
- https://newsn.net/say/react-useref.html
- https://newsn.net/say/react-usestate.html
- https://newsn.net/say/react-usememo.html
- https://newsn.net/say/react-useeffect.html
结束语
在本文中,通过组合useReducer的结果到context,实现了在各个子组件中不依靠props传值的效果。更多react经验文章,请点击苏南大叔的博客文章: