簡體   English   中英

我試圖設置我的 state,但它返回“無法在尚未安裝的組件上調用 setState”。 錯誤

[英]I tried to set my state, but it returns “Can't call setState on a component that is not yet mounted.” error

class Dashboard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      frontURL: null,
      backURL: null,
    };
  }

viewApplicant = (e) => {
    var driverID = e.target.parentElement.parentElement.id;

    firebase.storage()
      .ref("license/" + driverID)
      .child("front")
      .getDownloadURL()
      .then(frontURL => {
        this.setState({
          frontURL
        });
      }).catch(() => {
        alert('Front image could not be loaded')
      });


    firebase.storage()
      .ref("license/" + driverID)
      .child("back")
      .getDownloadURL()
      .then(backURL => {
        this.setState({
          backURL
        });
      }).catch(() => {
        alert('Back image could not be loaded')
      });
  }
}

I'm trying to get my image from Firebase storage, I am able to get the image URL but when I try to set my state to that of the URL, the warning message returned in the console always says that my component is not mounted,我不明白,因為據我了解,必須安裝一個組件才能進行渲染。 因此,我的圖像沒有顯示。

我是 React 的新手,任何關於為什么會發生這種情況的解釋都將不勝感激。

我已經檢查過以前的帖子,

  • 我沒有安裝react-hot-loader
  • 我已經在構造函數中初始化了我的狀態
  • 我檢查了我的組件是通過componentDidMount安裝的

我認為您應該使用變量 _isMounted 來檢查您的組件何時安裝。 閱讀更多: https://www.robinwieruch.de/react-warning-cant-call-setstate-on-an-unmounted-component

class Dashboard extends React.Component {
  _isMounted = false;
  constructor(props) {
    super(props);
    this.state = {
      frontURL: null,
      backURL: null,
    };
  }

  componentDidMount() {
    this._isMounted = true;

    firebase.storage()
      .ref("license/" + driverID)
      .child("front")
      .getDownloadURL()
      .then(frontURL => {
        if (_isMounted) {
          this.setState({
          frontURL
        });
        }
      }).catch(() => {
        alert('Front image could not be loaded')
      });
  }

  componentWillUnmount() {
    this._isMounted = false;
  }

  ....
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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