React:prop不会在父级重新呈现时传递给子组件

问题描述 投票:0回答:1

我的父组件中有这个代码:

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

reactjs
1个回答
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,因为在父组件中更新的状态将导致重新渲染,并且子组件中的游戏道具也将是更新。

© www.soinside.com 2019 - 2024. All rights reserved.