[英]React Native: Invariant Violation: Maximum update depth exceeded error
我知道當組件在componentWillUpdate
或componentDidUpdate
中重復調用setState
時會發生這種情況,但在我的情況下,即使我在此之后僅調用setState
一次,我也會收到此錯誤。 這是我的state
和componentDidUpdate
:
constructor(props) {
super(props);
this.state = { usernameAlreadyUsing: false };
}
componentDidUpdate() {
if(this.props.usernames.includes(this.props.username)) {
this.setState({ usernameAlreadyUsing: true });
}
}
每次調用componentDidUpdate
的setState
都會重新調用自己。 所以這種情況會導致你進入一個無限循環。
來試試這個
constructor(props) {
super(props);
this.state = { usernameAlreadyUsing: false };
}
componentDidUpdate() {
const { usernameAlreadyUsing } = this.state;
if(this.props.usernames.includes(this.props.username) && !usernameAlreadyUsing) {
this.setState({ usernameAlreadyUsing: true });
}
}
使用此實現,您的代碼僅在componentDidUpdate
中輸入一次。
希望它有效。
constructor(props) {
super(props);
this.state = { usernameAlreadyUsing: false };
}
componentDidUpdate(prevProps) {
if(this.props.usernames.length != prevProps.usernames.length) {
if(this.props.usernames.includes(this.props.username)) {
this.setState({ usernameAlreadyUsing: true });
}
}
}
嘗試。 這個,你上面的問題是,一旦它的設置用戶名已經存在,它會再次調用 setState 因為條件每次都成功。 嘗試這個
希望對您有所幫助。如有疑問,請隨意
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.