【问题标题】:Context.Consumer isn't using the value from Context.ProviderContext.Consumer 没有使用来自 Context.Provider 的值
【发布时间】:2019-08-16 03:23:23
【问题描述】:

我正在尝试使用 Context API 根据用户的登录状态来呈现 UI 组件。 Context.Consumer 似乎从 Context.Provider 获取值,但该值存储在 1 的键上,而 Consumer 的子函数正在从 0_currentValue 获取值。

如何让消费者使用新提供的值而不是默认值?

一些简化的代码 sn-ps...

<Layout /> 包裹所有页面,<MenuContent /><body /> 内部呈现


const { Provider, Consumer } = React.createContext("defaultValue");


function Layout() {
    return (
        <Provider value="newValue">
          <body>{props.body}</body>
        </Provider>
    );
  }


function MenuContent() {
  console.log('ConsumerObject:', Consumer);
  return(
    <Consumer>
      { value => console.log("value:", value) }
    </Consumer>
    );
  }

控制台打印:


value: "defaultValue"


ConsumerObject: {
  '$$typeof': Symbol(react.context),
  _context: {
    '0': 'defaultValue',
    '1': 'newValue',
    '$$typeof': Symbol(react.context),
    _calculateChangedBits: null,
    _currentValue: 'defaultValue',
    _currentValue2: 'defaultValue',
    _threadCount: 2,
    Provider: { '$$typeof': Symbol(react.provider), _context: [Circular] },
    Consumer: [Circular],
    _currentRenderer: null,
    _currentRenderer2: null
  },
  _calculateChangedBits: null
}

所以,我看到 newValue 位于 Consumer 对象上,但它似乎不在正确的位置,无法按照文档所示访问它。

希望我解释得足够好...提前致谢。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    我试过你的代码,看起来很正常。在您的消费者日志中,Consumer 的类型是 [Circular] 而不是 Symbol(react.context)

    【讨论】:

      猜你喜欢
      • 2019-11-10
      • 1970-01-01
      • 2020-07-19
      • 2019-08-27
      • 2020-11-15
      • 1970-01-01
      • 2021-08-26
      • 2021-07-15
      • 1970-01-01
      相关资源
      最近更新 更多