【问题标题】:How to access context data with useContext in the root/Parent entry?如何在根/父条目中使用 useContext 访问上下文数据?
【发布时间】:2019-12-21 19:39:21
【问题描述】:

这是codesandbox

我可以通过子组件成功获取和设置上下文数据。但是为什么我不能在父级中访问它们?

const App: React.FC = () => {
  const context = useContext(MyContext)
  return (
    <div className="App">
      <MyContextProvider>
        <Comp1 />
        <Comp2 />
        <p>
          Result inside: {context.selection}
        </p>
      </MyContextProvider>
      <p>
        Result outside: {context.selection}
      </p>
    </div>
  );
}

这是子组件。

const Comp1 = () => {
    const context = useContext(MyContext)
    return (
        <div>
            <p>current: {context.selection}</p>
            <button onClick={() => context.setSelection && context.setSelection(123)}>Set to '123'</button>
        </div>
    )
}

这是上下文文件。

interface MyContextProviderType {
    children: JSX.Element | JSX.Element[]
}

interface ContextProps {
    selection: string
    setSelection: Function
}

export const MyContext = createContext<Partial<ContextProps>>({})

export const MyContextProvider = ({children}: MyContextProviderType) => {
    const [selection, setSelection] = useState('')
    return (
        <MyContext.Provider value={{selection, setSelection}}>
            {children}
        </MyContext.Provider>
    )
}

感谢您的帮助!

【问题讨论】:

  • 你不能;要使用上下文,您必须在提供者中。
  • 这就是为什么我有内外尝试。
  • 你有不能在&lt;MyContextProvider&gt;中内外都包裹的用例吗?

标签: reactjs typescript react-hooks react-context


【解决方案1】:

调用的组件

useContext(MyContext)

必须在树中具有更高的匹配提供程序。 否则,该值将是您初始化上下文的任何值。 在这种情况下,这个空对象:

createContext<Partial<ContextProps>>({})

您可以在提供程序中渲染您的 App 组件以使您的沙箱工作

<MyContextProvider><App /></MyContextProvider>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-02
    • 2010-11-10
    • 2020-08-10
    • 2015-05-06
    • 2013-04-08
    • 2013-08-31
    • 2015-05-24
    • 1970-01-01
    相关资源
    最近更新 更多