由于props在getDerivedStateFromProps中发生更改,因此本地状态未更改

时间:2019-05-14 13:14:42

标签: reactjs react-native

在我的个人资料更新屏幕中,我想显示错误消息

constructor(props){
   super(props)
   this.state={isError:false,
               message:''} 
 }

 static getDerivedStateFromProps(nextProps, prevState) {
       if(nextProps.common.isFetching === false && nextProps.common.error === false) {
           return {isError:false, message:nextProps.common.message};
      } else if(nextProps.common.error === true){
           return {isError:true, message:nextProps.common.message};
        }
    }

    componentDidUpdate(prevProps) {
      if(this.props.common.isFetching === false) {
        if(!_.isEqual(this.props.common, prevProps.common) && this.props.common.error === false ) {
          ToastAndroid.show(this.props.common.message, ToastAndroid.SHORT);
          this.props.navigation.goBack()
        }
      }
    } 

 handleCloseNotification=()=>{
        this.setState({ isError: false});
  }  

render() {

  const showNotification = this.state.isError;
return (..............
        ...............
  <Notification
   showNotification={showNotification}
    handleCloseNotification= 
   {this.handleCloseNotification}
   type="Error"
   firstLine={this.state.message} />)}

如果prop为true,则本地状态isError为true,并显示错误消息。当我触发handleCloseNotification时,本地状态isError为false但是它仍然是正确的,错误消息没有消失,如何处理这种情况?

1 个答案:

答案 0 :(得分:0)

  

本地状态isError应该为false,但仍为true

确定吗?在console.log(showNotification)中用render进行确认

此标志/值可能已更改(为false),但是<Notification />showNotification属性更改没有反应-只能在安装时使用。

FIX:

<Notification />条件渲染(整个):

{showNotification && <Notification 
  // component props
/>}