我有一个模式组件,当setState更改时应调用该组件,但由于某种原因它没有更新。在第一个文件Im中,在渲染中设置以下内容。
<ModalParcel showModal={this.state.showModal} parcelToConfirm={this.state.dataForParcelToConfirm} />
在模态组件的builder()中,我设置了以下内容。
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()在初始创建时仅被调用一次。我的印象是,当我更新状态以显示模式时,构造函数将再次被调用,但这没有发生。
我基本上想更改状态以显示模式,然后重新运行render()。
constructor重新渲染组件时不会调用No ,它只会在初始渲染时被调用。
constructor
我认为,有两种方法可以解决问题:
1. 使用componentWillReceiveProps(){生命周期方法,只要props值发生任何变化,它将被调用,因此您可以在state此处更新Modal组件值showModal,如下所示:
componentWillReceiveProps(){
state
componentWillReceiveProps(nextProp){ this.setState({ show: nextProps.showModal }); }
根据DOC:
在已安装的组件接收新道具之前,将调用componentWillReceiveProps()。如果您需要更新状态以响应道具更改(例如,将其重置),则可以比较this.props和nextProps并在此方法中使用this.setState()执行状态转换。
2. 不要将props值存储在state变量中,而不能直接this.props.showModel在模型组件中使用,这样,只要props值发生任何更改,Modal组件都会获取更新后的值。
props
this.props.showModel