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.
Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
can't get my head around what im doing wrong here.
any help is appreciated.
CodePudding user response:
Your render
method is calling setState
, which will trigger render
to be called again.
You should not call setState
inside of renderOptions
.
CodePudding user response:
in renderRadio() -> values={this.renderOptions()}
you are calling the renderOptions function. that function calls the setState. then react rerender the component. this will create a loop. to avoid it, you should change values prop to 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);