React Native-在componentWillUnmount方法中取消所有订阅和异步任务

时间:2019-06-28 12:28:23

标签: reactjs react-native fetch

由于我的应用正在从API提取图像并按预期呈现结果。但是显示此警告对这个项目来说并不完整,给出的答案还不能解决我的问题。

此外,使用AbortController无法解决将信号作为参数传递给fetch调用并在AbortController.abort()中使用componentWillUnmount的问题

Warning: Can't perform a React state update on an unmounted component. 
This is a no-op, but it indicates a memory leak in your application. 
To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount 
method.

代码:

componentDidMount() {
    this.getImage(Flikr_URL);
  }

  getImage(url) {
    fetch(url)
      .then(response => response.json())
      .then(responseJson =>
        this.setState({
          imageData: responseJson.photos.photo,
          loading: false
        })
      )
      .catch(err => {
        console.log(err);
        throw error;
      });
  }

  componentWillUnmount() {
    this.getImage();
  }

1 个答案:

答案 0 :(得分:0)

如果您想要简单的解决方案,这将为您提供帮助。也许会有另一个好的解决方案,但是现在您可以这样做。

手动检查是否已安装组件。 然后在componentDidMount方法中,将标志componentMounted设置为true。

  componentDidMount() {
    this.componentMounted = true;
    this.getImage(Flikr_URL);
  }
  getImage(url) {
    fetch(url)
      .then(response => response.json())
      .then(responseJson => {
        if (this.componentMounted) { // check here component is mounted
          this.setState({
            imageData: responseJson.photos.photo,
            loading: false
          });
        }
      })
      .catch(err => {
        console.log(err);
        throw error;
      });
  }

在componentWillUnmount方法中,将标志设置为false

  componentWillUnmount() {
    this.componentMounted = false;
  }