我试图在compenetdiUpdate设置状态,但它显示错误无限循环。有什么解决办法吗?最初我把setState放在一个函数中,但也面临这个错误。我用的是类组件代码
componentDidUpdate(){
if(isEmpty(this.props.AESDetail) == false){
if(this.props.AESDetail.length != 0){
if(this.props.APIESDetail.length != 0){
if(this.props.APIESDetail.Focus != null){
this.setState({
gotFocusApies: true
})
}
}
}
}
}
错误:超过最大更新深度。当组件在componentWillUpdate或componentDidUpdate内重复调用setState时,可能会发生这种情况。React限制嵌套更新的数量以防止无限循环。
看起来您可能只需要一个额外的测试来确保gotFocusApies
尚未true
。
这些if语句也最好合并成一个。注意:列表。长度!=0通常可以替换为
列表。长度
或!!列表长度
。
componentDidUpdate() {
if (
isEmpty(this.props.AESDetail) == false &&
this.props.AESDetail.length &&
this.props.APIESDetail.length &&
this.props.APIESDetail.Focus != null &&
!this.state.gotFocusApies
) {
this.setState({ gotFocusApies: true });
}
}