gpt4 book ai didi

javascript - 警告 : Cannot update during an existing state transition (such as within `render` or another component's constructor)

转载 作者:行者123 更新时间:2023-12-01 02:33:20 26 4
gpt4 key购买 nike

请帮忙

错误

Warning: Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount.

我的 react 代码

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

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

最佳答案

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

“setState() 并不总是立即更新组件。它可能会批量或推迟更新。这使得在调用 setState() 后立即读取 this.state 成为潜在的陷阱。相反,请使用 componentDidUpdate 或 setState 回调( setState(updater,callback)),其中任何一个都保证在应用更新后触发”

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

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

关于javascript - 警告 : Cannot update during an existing state transition (such as within `render` or another component's constructor),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48146556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com