簡體   English   中英

React Native:不變違規:超過最大更新深度錯誤

[英]React Native: Invariant Violation: Maximum update depth exceeded error

我知道當組件在componentWillUpdatecomponentDidUpdate中重復調用setState時會發生這種情況,但在我的情況下,即使我在此之后僅調用setState一次,我也會收到此錯誤。 這是我的statecomponentDidUpdate

constructor(props) {
    super(props);
    this.state = { usernameAlreadyUsing: false };
}

componentDidUpdate() {
    if(this.props.usernames.includes(this.props.username)) {
        this.setState({ usernameAlreadyUsing: true });
    }
}

每次調用componentDidUpdatesetState都會重新調用自己。 所以這種情況會導致你進入一個無限循環。

來試試這個

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM