简体   繁体   English

React - 使用多个 createContexts 的最佳方式是什么?

[英]React - What is the Best Way to use Multiple createContexts?

I've just learned about the createContext hook and I'm wondering what's the best approach to using multiple contexts globally throughout the project.我刚刚了解了 createContext 钩子,我想知道在整个项目中全局使用多个上下文的最佳方法是什么。

From what I've seen if you want to create and use multiple contexts it looks kinda messy having multiple nested Context tags and I'm wondering if there is a cleaner looking way of doing this?从我所见,如果你想创建和使用多个上下文,它看起来有点乱,有多个嵌套的上下文标签,我想知道是否有一种更简洁的方式来做到这一点?

(Example of how I think a project using four contexts would look) (我认为使用四个上下文的项目的外观示例)

import React, { createContext, useState } from "react";

export const OneContext = createContext();
export const TwoContext = createContext();
export const ThreeContext = createContext();
export const FourContext = createContext();

export default function App(){
    const [one, setOne] = useState(null);
    const [two, setTwo] = useState(null);
    const [three, setThree] = useState(null);
    const [four, setFour] = useState(null);

   return(
        <>
            <OneContext.Provider value={one}>
                <TwoContext.Provider value={two}>
                    <ThreeContext.Provider value={three}>
                        <FourContext.Provider value={four}>            
                            "Insert components here"
                        <FourContext.Provider />
                    <ThreeContext.Provider />
                <TwoContext.Provider />
            <OneContext.Provider />
        </>
   )
}

You can do something like that你可以做这样的事情

<AppContext.Provider
  value={{
    oneCTX: [one, setOne],
    twoCTX: [two, setTwo],
    threeCTX: [three,setThree]
  }}
>
  {props.children}
</AppContext.Provider>

on the other files, you can call them like this, Import AppContext from the context.js file first, then do that在其他文件上,您可以像这样调用它们,首先从 context.js 文件中导入 AppContext,然后执行此操作

const { oneCTX } = useContext(AppContext);
const [one, setOne] = loggedUserCTX;

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.当您有涉及多个子值的复杂 state 逻辑或下一个 state 取决于前一个时, useReducer通常比 useState 更可取。

import React, { createContext, useReducer } from "react";

const OneContext = createContext();

const initialState = {one:null, two:null, three:null, four:null};

function reducer(state, action) {
  return {
    ...state,
    [action.type]: action.payload
  }
}

export default function App(){
   const stateAndDispatch = useReducer(reducer, initialState)
   return(
        <>
            <OneContext.Provider value={stateAndDispatch}>       
                "Insert components here"
            <OneContext.Provider />
        </>
   )
}

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

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