简体   繁体   English

React:为什么我的上下文值没有更新?

[英]React: Why isn't my context value updated?

I'm playing with React Context API.我正在玩 React Context API。 I created a simple component:我创建了一个简单的组件:

import React, { createContext, useContext } from 'react';

const MyContext = createContext(1);

const MyComponent = () => (
    <>
        <p>{useContext(MyContext)}</p>
        <MyContext.Provider value={2}>
            <p>{useContext(MyContext)}</p>
        </MyContext.Provider>
    </>
);

export default MyComponent;

I'm getting two <p>1</p> .我得到两个<p>1</p> Why isn't the second context updated with 2 ?为什么不使用2更新第二个上下文? Am I using useContext() incorrectly?我是否错误地使用useContext()

You must use a separate Component to get Context to work.您必须使用单独的组件才能使 Context 正常工作。

I've filed a bug about this;我已经提交了一个关于这个的错误; see https://github.com/facebook/react/issues/18629https://github.com/facebook/react/issues/18629

Simply split the code using the Context into a different Component.只需使用 Context 将代码拆分为不同的组件。

const Inner = () => (
    <p>{useContext(MyContext)}</p>
);

const MyComponent = () => (
    <>
        <p>{useContext(MyContext)}</p>
        <MyContext.Provider value={2}>
            <Inner />
        </MyContext.Provider>
    </>
);

That should fix it.那应该解决它。

You'll need to render another component inside the context provider to get the value of 2. As useContext 's documentation states:您需要在上下文提供程序中呈现另一个组件以获得 2 的值。正如useContext的文档所述:

Accepts a context object (the value returned from React.createContext) and returns the current context value for that context.接受上下文 object(从 React.createContext 返回的值)并返回该上下文的当前上下文值。 The current context value is determined by the value prop of the nearest <MyContext.Provider> above the calling component in the tree .当前上下文值由树中调用组件上方最近的 <MyContext.Provider> 的 value 属性确定。

Emphasis added.重点补充。 The important point is that it doesn't matter where you call useContext inside the component - what matters is where that component where it's called in is located in the tree.重要的一点是,在组件内调用useContext的位置无关紧要 - 重要的是调用它的组件在树中的位置。

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

const MyContext = createContext(1);

const ChildComponent = () => (
  <p>{useContext(MyContext)}</p>
)

const MyComponent = () => (
  <>
      <p>{useContext(MyContext)}</p>
      <MyContext.Provider value={2}>
        <ChildComponent/>
      </MyContext.Provider>
  </>
);

export default MyComponent;

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

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