我是 React 的新手,我正面临与状态更新相关的问题。
我有一个父组件。在父组件构造函数中,我创建了子组件的多个实例。
使用父组件的状态,我显示一个子组件实例。
子组件的实例具有一些作为道具传递的父组件状态值。
父组件状态如下所示(我已简化代码,以便更清晰)
displayedContainer: {...} // An Instance of Child Component
isLoading: false
父组件构造函数如下所示
constructor(props) {
super(props);
// Create state
this.state = {
isLoading: false,
displayedContainer: null
};
// Create all Child Component (Container)
this.defaultComponent = <Container
isLoading={this.state.isLoading}
></Container>
// Others Child Component are created the same way as above.
// To clearify the code i have removed them.
}
这是渲染方法
render() {
return (
<div>
{this.state.displayedContainer}
<div className="container-left-bar"></div>
</div>
)
}
从那里,我可以从一个子组件显示切换到另一个,这样它就state.displayedContainer
可以工作了。但是当state.isLoading
更新时,子组件不会检测到它。我认为这是因为我在构造函数中创建了子组件。
如果我想在渲染之前保留创建子组件的逻辑但修复未检测到状态更新的问题,我该怎么办?
谢谢您的帮助 !