【问题标题】:React - Context structure issueReact - 上下文结构问题
【发布时间】:2020-10-16 08:54:51
【问题描述】:

简而言之,我在项目的根目录中获得了一个全局上下文——它被提供给子组件。其中一个子组件本身需要是上下文提供者,但它的子组件需要访问这两个上下文。

虽然我可以将字段附加到第一个上下文(例如解构上下文并向子对象添加更多内容),但我不知道如何。

然后我创建了另一个上下文(子上下文)并包装了子上下文,但是当我访问它时,只有子上下文可用,而不是全局上下文。

示例。

// DrawerContext Context component
import React, { createContext } from 'react'
const DrawerContext = createContext()
export default DrawerContext

// GlobalContext Context component
import React, { createContext } from 'react'
const GlobalContext = createContext()
export default GlobalContext

---

// So root has ..
 <GlobalContext.Provider value={{ 
              someValue: someValue }}>
              <Child />
</GlobalContext.Provider>

// Child has ...

<DrawerContext.Provider value={{
        anotherValue: anotherValue
        }}>
          <subChild />
</DrawerContext.Provider>

// Subchild ...
const drawerContext = useContext(DrawerContext) // This has values
const context = useContext(GlobalContext) // This is undefined .. :(

【问题讨论】:

    标签: reactjs react-context


    【解决方案1】:

    抱歉,我测试的方式省略了实际的 GlobalContext - 这就是它未定义的原因。

    上面的代码示例运行良好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多