反应:prop在父级渲染时未传递给子组件

时间:2018-07-19 17:13:41

标签: reactjs

我的父组件中包含以下代码:

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之后,每次调用parent中的componentWillReceiveProps时。但是,尽管this.state.game具有属性,但是nextProps.game是一个空对象。

怎么可能?

我使用React 16.2

1 个答案:

答案 0 :(得分:2)

如果您真的想将游戏用作LaunchSidebar组件中的状态,建议您将componentWillReceiveProps方法与componentDidUpdate交换。

例如:

componentDidMount(prevProps, prevState) {
    if (prevState.game !== this.props.game) {
        this.updateGame(this.props.game);
    }
}

updateGame = (game) => {
    this.setState({ game });
}

请注意,为了更新componentDidMount生命周期方法内的状态,您应该将其包装在有条件的包装中,否则它将陷入循环中。

我会考虑保持其简单性,并在父组件中更新游戏,并将其用作子组件中的道具,因为在父组件中更新的状态将导致重新渲染,并且子组件中的游戏道具也会被更新。