我们相信:世界是美好的,你是我也是。平行空间的世界里面,不同版本的生活也在继续...

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

苏南大叔:react,useReducer结合useContext跨组件状态管理终极版 - 状态管理终极版
react,useReducer结合useContext跨组件状态管理终极版(图4-1)

大家好,这里是苏南大叔的平行空间笔记本博客,这里记录苏南大叔和计算机代码的故事。本文继续描述react项目的useReduceruseContext的跨组件状态管理的终极版。测试环境:create-react-app@5.0.1node@16.14.2react@18.2.0react-dom@18.2.0

基本内容

为了更好的理解本文的内容,推荐大家阅读一下本文的前置内容:

本文的代码和上一篇文章中的代码基本雷同,有区别的地方就是改进之处。主要的思路就是,把useReducer的的结果statedispatch再进行从新进行组合,然后传入prodivervalue中。在各个被嵌套的组件中,可以通过useContext获得上述statedispatch的组合。

苏南大叔:react,useReducer结合useContext跨组件状态管理终极版 - 运行截图
react,useReducer结合useContext跨组件状态管理终极版(图4-2)

定义contextreducerprodiver

这里对做contextreducer基本定义,注意这里给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 }}>

苏南大叔:react,useReducer结合useContext跨组件状态管理终极版 - provider-code
react,useReducer结合useContext跨组件状态管理终极版(图4-3)

定义内部嵌套组件

function SunanInner() {
    const ctx = useContext(sunanContext);
    function handleClick() {
        ctx.sunanDispatch({ type: 'add', text: '高兴' });
    }
    return (
        <>
            子组件接收状态:{ctx.text} &nbsp;
            <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' });

苏南大叔:react,useReducer结合useContext跨组件状态管理终极版 - usecontext-dispatch
react,useReducer结合useContext跨组件状态管理终极版(图4-4)

相关文章

结束语

在本文中,通过组合useReducer的结果到context,实现了在各个子组件中不依靠props传值的效果。更多react经验文章,请点击苏南大叔的博客文章:

如果本文对您有帮助,或者节约了您的时间,欢迎打赏瓶饮料,建立下友谊关系。
本博客不欢迎:各种镜像采集行为。请尊重原创文章内容,转载请保留作者链接。

 【福利】 腾讯云最新爆款活动!1核2G云服务器首年50元!

 【源码】本文代码片段及相关软件,请点此获取更多信息

 【绝密】秘籍文章入口,仅传授于有缘之人   react