![](/img/trans.png)
[英]React Context Api - A Context Passed through Context Provider is yet not able to accessible by Child Components
[英]Is React context provider not mounted before child components?
如何在安装组件之前确保在上下文提供程序中设置值?
在下面的代码示例中,将首先记录子组件(仪表板)中的console.log(未定义)。 为什么这样,有没有办法确保在安装该组件之前设置该值?
App.js
render() {
return (
<div className='App'>
<ContextProvider>
<Dashboard />
</ContextProvider>
</div>
);
}
ContextProvider.js
componentDidMount = () => {
this.setState({value: 1})
console.log(this.state.value);
}
Dashboard.js
componentDidMount = () => {
console.log(this.context.value);
}
孩子们先被渲染。 无论如何, setState
是异步的,因此将异步地向消费者提供上下文。
如果孩子有必要等待上下文,他们应该有条件地呈现:
render() {
this.context.value && ...
}
或者使用上下文使用者包装,可以将其编写为HOC以供重用:
const withFoo = Comp => props => (
<FooContext.Consumer>{foo => foo.value && <Comp {...props}/>}</FooContext.Consumer>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.