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

React: Why isn't my context value updated?

我正在玩 React Context API。我创建了一个简单的组件:

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;

我要两个 <p>1</p>。为什么不使用 2 更新第二个上下文?我是不是用错了useContext()

您必须使用单独的组件才能使上下文正常工作。

我已经提交了一个关于这个的错误;见 https://github.com/facebook/react/issues/18629

简单地将使用上下文的代码拆分到不同的组件中。

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

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

这应该可以解决问题。

您需要在上下文提供程序中呈现另一个组件以获得 2 的值。如 useContext 的文档所述:

Accepts a context object (the value returned from React.createContext) and returns the current context value for that context. The current context value is determined by the value prop of the nearest <MyContext.Provider> above the calling component 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;