[英]Error: Maximum update depth exceeded. setState throws error
export class ABC extends React.Component {
constructor(props) {
super(props);
this.state = {
abc: null
};
}
renderOptions() {
this.setState({
abc: abcArray.length !== 0
});
return;
}
renderRadio() {
return (
<Field
id="abc"
name="abc"
values={this.renderOptions()}
/>
);
}
render() {
return (
<div>
{this.renderRadio()}
</div>
);
}
}
export default connect(mapStateToProps)(ABC);
I am trying to setState in renderOptions() which gives me the below error.我正在尝试在 renderOptions() 中设置状态,这给了我以下错误。
Error: Maximum update depth exceeded.错误:超过最大更新深度。 This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React limits the number of nested updates to prevent infinite loops. React 限制了嵌套更新的数量以防止无限循环。
can't get my head around what im doing wrong here.无法理解我在这里做错了什么。
any help is appreciated.任何帮助表示赞赏。
Your render
method is calling setState
, which will trigger render
to be called again.您的render
方法正在调用setState
,这将触发再次调用render
。
You should not call setState
inside of renderOptions
.您不应该在renderOptions
中调用setState
。
in renderRadio() -> values={this.renderOptions()}
you are calling the renderOptions function.在 renderRadio() -> values={this.renderOptions()}
你正在调用 renderOptions function。 that function calls the this.setState({abc: abcArray.length;== 0});
function 调用this.setState({abc: abcArray.length;== 0});
. . then react will try to rerender the component.然后 react 将尝试重新渲染组件。 this will create a loop.这将创建一个循环。 to avoid it, you should change values prop to this values={this.renderOptions}
为避免这种情况,您应该将 values 属性更改为 this values={this.renderOptions}
I've refactor your code.我已经重构了你的代码。
export class ABC extends React.Component {
constructor(props) {
super(props);
this.state = {
abc: null
};
}
renderOptions() {
this.setState({
abc: abcArray.length !== 0
});
return;
}
renderRadio() {
return (
<Field
id="abc"
name="abc"
values={this.renderOptions}
/>
);
}
render() {
return (
<div>
{this.renderRadio()}
</div>
);
}
}
export default connect(mapStateToProps)(ABC);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.