使用 reactjs 中的props更改更新状态值

IT技术 reactjs react-native
2021-05-10 17:37:28

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

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

在模态组件构造函数()中,我设置了以下内容。

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 );

  }

问题是构造函数() 只在初始创建时被调用一次。我的印象是,当我更新状态以显示模态时,构造函数将再次被调用,但这并没有发生。

我基本上想更改状态以显示模态,然后重新运行 render()。

1个回答

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

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

1.使用componentWillReceiveProps(){生命周期方法,它会在 props 值发生任何更改时被调用,因此您可以在state此处更新 Modal 组件值 showModal,如下所示:

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

根据DOC

componentWillReceiveProps() 在挂载的组件接收新的 props 之前被调用。如果您需要更新状态以响应 prop 更改(例如,重置它),您可以比较 this.props 和 nextProps 并在此方法中使用 this.setState() 执行状态转换。

2.不要将props存储state变量中,而是直接this.props.showModel在Model组件中使用,这样每当props值发生任何变化时,Modal组件都会获取更新的值。