繁体   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