我的父组件中有这个代码:
render () {
return (
<div>
<LaunchSidebar game={this.state.game} />
{!this.state.isLaunchingGame && <Loader/>}
<div ref="game-container" id="game-container"></div>
</div>
)
}
在LaunchSidebar
:
componentWillReceiveProps(nextProps) {
this.setState({ game: { ...nextProps.game }});
}
我设置了断点,并且在调用render
之后,每次调用父级中的componentWillReceiveProps
时都会看到它。然而,虽然this.state.game
有属性,但nextProps.game
是一个空对象。
怎么可能呢?
我使用React 16.2
如果您真的想在LaunchSidebar组件中将游戏用作状态,我建议您将componentWillReceiveProps方法与componentDidUpdate交换。
例如:
componentDidMount(prevProps, prevState) {
if (prevState.game !== this.props.game) {
this.updateGame(this.props.game);
}
}
updateGame = (game) => {
this.setState({ game });
}
注意,为了更新componentDidMount生命周期方法中的状态,您应该将其包装在条件中,否则它将被卡在循环中。
我会考虑保持简单并更新父组件中的游戏并将其用作子组件中的prop,因为在父组件中更新的状态将导致重新渲染,并且子组件中的游戏道具也将是更新。