[英]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.