警告:在现有状态转换期间无法更新(例如在`render`或其他组件的构造函数中)

时间:2018-01-08 08:27:14

标签: javascript reactjs

请帮忙

错误

  

警告:在现有状态转换期间无法更新(例如   在render或其他组件的构造函数中)。渲染方法   应该是道具和国家的纯粹功能;构造函数的副作用   是一种反模式,但可以移到componentWillMount

我的反应代码

    componentWillReceiveProps(nextProps){
        this.setState({appointment: nextProps.appointment })
        this.setState({responseObj: nextProps.responseObj })
     }


    render() {
        const appointment =   this.state.appointment;
        const responseObj = this.state.responseObj;
        const userId = this.props.userId;

        let content = null;
        let message = null;

         if(appointment === null ){
            content = 'loading ...';
        }

         if(appointment ===  false) 
            if(responseObj) {
                if(responseObj.data.errno === 1062){    
                    message = <div>appointment became unavailable.   </div>;
            }   
        }
        else {  
            content =  "no records ";
        }


            if(responseObj)
                if(responseObj.data.errno === 1062){    
                    message = "sorry, cannot reserve more than one appointment"   ;
                 }

        if(appointment )
        content = <SimpleMediaCard userId={userId} appointment={appointment} /> ;

        return( 
            <div>
                    {content}{ message}

            </div>
            );


    }
}


function mapStateToProps({appointment, responseObj }, ownProps){    

    return {appointment: appointment,
            responseObj: responseObj
     }
}

export default connect(mapStateToProps, mapDispatchToProps )(SavedAppointments);    

我删除了不必要的代码,如果您对此感兴趣,请告诉我。

1 个答案:

答案 0 :(得分:2)

来自https://reactjs.org/docs/react-component.html#setstate

&#34; setState()并不总是立即更新组件。它可以批量推迟更新或推迟更新。这使得在调用setState()之后立即读取this.state是一个潜在的陷阱。相反,使用componentDidUpdate或setState回调(setState(更新程序,回调)),其中任何一个都保证在应用更新后触发&#34;

在我看来,您应该在使用之前检查是否创建了以下对象,或者在setState()内放置回调。

  const appointment =   this.state.appointment;
  const responseObj = this.state.responseObj;
  const userId = this.props.userId;