react,useReducer结合useContext实现跨组件状态管理
发布于 作者:苏南大叔 来源:程序如此灵动~
来复述一下目前的两个观点:useReducer状态管理是useState的升级版,useContext可以跨组件实现数据/函数的传递。如果想要执行一个action,那么可以从context中获得dispatch,继而修改状态数据。总的思路就是,使用useReducer生成加强版本的state和dispatch,然后通过context提供给全部组件使用。

大家好,这里是苏南大叔的程序如此灵动博客,这里记录苏南大叔和计算机代码的故事。本文描述react中的useReducer和useContext结合,在组件中传递执行数据的组合写法。测试环境:create-react-app@5.0.1,node@16.14.2,react@18.2.0,react-dom@18.2.0。
前文回顾
本文的正确理解,可能需要您查看下面三篇文章:
props传递: https://newsn.net/say/react-props.htmluseContext使用:https://newsn.net/say/react-context.htmluseReducer使用:https://newsn.net/say/react-usereducer.html

定义reducer和context
import React, { useReducer, useContext } from 'react';
const sunanContext = React.createContext(null);
const sunanReducer = (state, action) => {
switch (action.type) {
case "add":
return {...state, text: action.text}
default:
throw Error();
}
}
定义Provider,传递props
function SunanComponent() {
const [sunanState, sunanDispatch] = useReducer(sunanReducer, { text: "----" });
return (
<sunanContext.Provider value={sunanDispatch}>
<SunanOuter sunan={sunanState} />
</sunanContext.Provider>
);
}
export default SunanComponent;定义展示组件
function SunanInner(props) {
const dispatch = useContext(sunanContext);
function handleClick() {
dispatch({ type: 'add', text: '高兴' });
}
return (
<>
子组件接收状态:{props.sunan.text}
<button onClick={handleClick.bind()}>High起来</button>
</>
);
}
function SunanOuter(props) {
return <>
苏南大叔的心情:{props.sunan.text}<br /><br />
<SunanInner sunan={props.sunan} />
</>
}
如果要仔细查看代码的话,本文的代码最大的问题就在这里了。虽然多层嵌套的组件,可以通过context功能获得dispatch函数,从而获得执行action的能力。但是,修改state数据后,还是需要通过props层层向下传递,如果层级比较多的话,这仍然是个大问题。所以,这里的状态变量传递写法是有问题的。解决方案是什么呢?请关注苏南大叔的后续文章。
相关链接
- 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
结束语
更多react相关经验文章,请参考苏南大叔的博客: