[英]componentDidUpdate - Error: Maximum update depth exceeded
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
:我试图根据道具更改设置状态,但是我在
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. componentDidUpdate
被调用,它设置状态,触发componentDidUpdate
... 一轮又一轮。
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>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.