简体   繁体   English

这是使用 React 上下文的好设计吗? API

[英]Is this a good design for using React context API

I am working on a React project which is divided into several modules and each module contains several components.我正在开发一个 React 项目,该项目分为几个模块,每个模块包含几个组件。 There is also a commons module which contains components which are common to two or more separate modules.还有一个commons模块,其中包含两个或多个单独模块共有的组件。 I am using context API for managing all the state.我正在使用上下文 API 来管理所有 state。 Below is the structure of the parent component(App.js).下面是父组件(App.js)的结构。 Module1Container , Module2Container ... contains components of respective modules. Module1Container , Module2Container ... 包含各个模块的组件。

return(
    <CommonsContextProvider>
        <Module1ContextProvider>
            <Module1Container />
        </Module1ContextProvider>
        <Module2ContextProvider>
            <Module2Container />
        </Module2ContextProvider>
        <Module3ContextProvider>
            <Module3Container />
        </Module3ContextProvider>
    </CommonsContextProvider>
)

I mainly want the states to be seperate as a single context for every module will make it too much cluttered.我主要希望将状态分开,因为每个模块的单个上下文会使其过于混乱。 Is it a good idea to have a separate context for each module and a common context for commonly used state across modules?为每个模块设置一个单独的上下文并为跨模块的常用 state 设置一个通用上下文是个好主意吗? Don't this structure voids the single source of truth rule?这种结构不是使单一事实来源规则无效吗? Better suggestion is most welcome.更好的建议是最受欢迎的。

This method currently have no problem, but on the long run, if you need to maintain the project single source of truth is still better,这种方法目前没有问题,但是从长远来看,如果需要维护项目单源还是比较好的,

For single source of truth use redux (redux-hooks) and incase you need to have modular kinda of view of states use different reducers for different component and common reducer for global state,then combine them using combineReducer of redux对于单一事实来源,请使用 redux(redux-hooks),以防您需要模块化的状态视图,对不同的组件使用不同的减速器,为全局 state 使用通用减速器,然后使用 Z7490FE17CAEC3723E8 的 combineReducer 组合它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM