在现有状态转换期间更新(例如在"render"中)出现错误


class NewComponent extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
obj: [],
externalObj: [],
};
}
getFunc = (external) => {
...
arr = arr.filter(a => a.toLowerCase().includes('eg')
this.setState({ obj: arr });

return arr.map((Id) => {
return <Legend key={Id} id={Id} title={Id}/>;
});
}
render() { 
return(
this.getFunc(false);
)
}
}

这是我的React组件的结构。我想将obj的状态设置为arr,以便在其他完全不同的方法中使用obj我得到了这个错误-Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state.

我有点知道是什么导致了这个错误,但我不知道我还能做什么来实现我想要的——能够在另一种叫做单独的方法中使用这个arr

您正在渲染函数内部设置状态,因此当它尝试渲染它时,它将设置新状态并再次渲染,这可能会导致无限循环。

我不确定这行this.setState({ obj: arr });做什么,但它应该被移到componentDidMount或componentDidUpdate中的某个地方,或者你需要它的地方

您可以使用其中一种生命周期方法制作过滤器,然后从状态渲染数组

更新

在您的课堂上添加组件DidMount

componentDidMount(){
arr = arr.filter(a => a.toLowerCase().includes('eg')
this.setState({ obj: arr });
}

然后在您的getFunc 中

return this.state.obj && this.state.obj.map((Id) => {
return <Legend key={Id} id={Id} title={Id}/>;
});

最新更新