在ReactJS中,使用props更改更新状态值

4

我有一个模态组件,应该在 setState 改变时被调用,但是由于某种原因它没有更新。在第一个文件中,在 render 中设置如下内容。

<ModalParcel showModal={this.state.showModal} parcelToConfirm={this.state.dataForParcelToConfirm} />

在Modal组件的constructor()中,我设置了以下内容。

constructor(props) {
    super(props);

    console.log("Constructor for modal componenet called.")

    //this.renderRowForMain = this.renderRowForMain.bind(this);

    this.state = {
      show: this.props.showModal
    };

  }

render() {

    if(this.state.show == true){

        var content = 
        <View style={styles.modal}>
            <View style={styles.modalContent}>
                <TouchableHighlight onPress={() => this.closeModal()}>
                    <Text>Close</Text>
                </TouchableHighlight>
            </View>
        </View>;

    }else {

        var content = null;

    }

    return ( content );

  }

问题在于constructor()仅在初始创建时调用一次。我以为当我更新状态以显示模态框时,constructor会再次被调用,但事实并非如此。我基本上想改变状态来显示模态框,然后重新运行render()。
1个回答

5

当组件重新渲染时,constructor不会被调用,它只会在初始渲染时被调用。

我认为,有两种方法可以解决您的问题:

1. 使用componentWillReceiveProps()生命周期方法,每当props值发生变化时都会调用它,因此您可以在此处更新Modal组件的state值showModal,如下所示:

componentWillReceiveProps(nextProp){
   this.setState({
      show: nextProps.showModal
   });
}

根据文档所述:
在已挂载组件接收到新属性之前,将调用componentWillReceiveProps()。如果您需要响应属性更改更新状态(例如重置状态),可以在此方法中使用this.props和nextProps进行状态转换,并使用this.setState()。
2.不要将props值存储在state变量中,而是直接在Modal组件中使用this.props.showModel。通过这种方式,每当发生任何更改时,Modal组件都会获取更新后的值。

谢谢回复,我刚试过了,效果非常好。 - ORStudios

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接