class Suggestions extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: false
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
console.log(event.target.value)
}
componentDidUpdate(props, state) {
if(props.dataSearchBox) {
this.setState({visible: true})
} else {
this.setState({visible: false})
}
}
render() {
return (
<div className={`g${this.state.visible === true ? '': ' h'}`}>
<ul>
</ul>
</div>
);
}
}
export default Suggestions;
I am trying to set the state based on the props change, however I get the following error inside componentDidUpdate
:
There was an 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.
What am I doing wring here?
Your problem is here:
componentDidUpdate(props, state) {
if(props.dataSearchBox) {
this.setState({visible: true})
} else {
this.setState({visible: false})
}
}
componentDidUpdate
gets called, it sets the state, which triggers componentDidUpdate
... round and round.
Do you need a separate state property to handle this? That's a bit of an anti-pattern - you have what you need already as a prop, just use its value to control the visibility directly:
render() {
return (
<div className={`g${this.props.dataSearchBox ? '': ' h'}`}>
<ul>
</ul>
</div>
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.