简体   繁体   English

是否在子组件之前安装了React上下文提供程序?

[英]Is React context provider not mounted before child components?

How do I make sure I set a value in the context provider before components are mounted? 如何在安装组件之前确保在上下文提供程序中设置值?

In the code example below, the console.log in the child component(Dashboard) will be logged first (as undefined). 在下面的代码示例中,将首先记录子组件(仪表板)中的console.log(未定义)。 Why is that and is there any way for me to make sure the value is set before that component is mounted? 为什么这样,有没有办法确保在安装该组件之前设置该值?

App.js App.js

render() {
  return (
    <div className='App'>
      <ContextProvider>
        <Dashboard />
      </ContextProvider>
    </div>
  );
}

ContextProvider.js ContextProvider.js

componentDidMount = () => {
  this.setState({value: 1})
  console.log(this.state.value);
}

Dashboard.js Dashboard.js

componentDidMount = () => {
  console.log(this.context.value);
}

Children are rendered first. 孩子们先被渲染。 Regardless of that, setState is asynchronous, so a context will be provided to consumers asynchronously. 无论如何, setState是异步的,因此将异步地向消费者提供上下文。

In case there's a necessity for children to wait for a context, they should be either conditionally rendered: 如果孩子有必要等待上下文,他们应该有条件地呈现:

render() {
  this.context.value && ...
}

Or be wrapped with context consumer which can be written as a HOC for reuse: 或者使用上下文使用者包装,可以将其编写为HOC以供重用:

const withFoo = Comp => props => (
  <FooContext.Consumer>{foo => foo.value && <Comp {...props}/>}</FooContext.Consumer>
);

暂无
暂无

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

相关问题 React 上下文 Api - 通过上下文提供程序传递的上下文仍无法被子组件访问 - React Context Api - A Context Passed through Context Provider is yet not able to accessible by Child Components 反应上下文重新渲染提供者的每个孩子? - react context rerenders every child of Provider? 从子组件向 React 上下文添加值 - Add value to React context from child components 子代反应组件中的易变上下文和executeAction - Fluxible context and executeAction in child react components 如何在 React 的父上下文提供程序中定义子上下文提供程序中的函数? - How to define functions in Child Context Provider from Parent Context Provider in React? 如何在安装 React 组件之前让 Saga 监视事件? - How can I make Saga watch events before the React components are mounted? 反应上下文提供者和消费者 - React context provider and consumer 反应 memory 泄漏 - 通过 function 在上下文提供者中更新 state 时传递给提供者的孩子 - React memory leak - when updating state in context provider via a function passed to a child of the provider componentDidMount() State 上下文提供程序中的更改不会触发子组件上的重新渲染 - componentDidMount() State Change in Context Provider not triggering re-render on Child Components 当我更新 context.provider 的值时,子组件不会改变颜色 - When I update my context.provider's value, the child components don't change color
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM