警告:只能在setInterval(React Native)中调用api时更新已安装或安装的组件

Ros*_*tam 0 javascript android ios reactjs react-native

我一直在开发一个应用程序,我需要每30秒进行一次API调用,并在某些状态下设置响应.我在setInterval里面做.我有一个组件,在应用程序的所有屏幕上呈现.(setInterval所在的组件).一切似乎都有效,但是当我按下后退按钮进入上一个屏幕时,我得到了这个警告'setState on unmounted component'.请记住,组件也会再次安装在此屏幕中.足够的话,让我在这里有代码.

SongActivityBar.js

componentDidMount(){
  _isMounted = true
  this._timer = true;
  this.startPolling();
}


  componentWillUnMount() {
    _isMounted = false;
    this._timer && clearInterval(this._timer);
    this._timer = false;
  }

  startPolling=() => {
      if (_isMounted){
          this.fetchNowPlaying(); // do it once and then start it up ...
          this._timer = setInterval(() => this.fetchNowPlaying(), 30000);
      }
  }


 fetchNowPlaying() {
    fetch(url, {
    .......... 
    .then( (response) => {
      this._timer && this.setState({loading: false, nowPlaying: response.Message});
    ........
    });
  }
Run Code Online (Sandbox Code Playgroud)

当点击应用程序的任何屏幕时,组件SongActivityBar.js被加载,回到任何屏幕,使用nav.pop()或android后退按钮给我这个警告.

PS:我使用Navigator在屏幕之间导航(现在无法更改库)

React Native version - 0.45.1
Run Code Online (Sandbox Code Playgroud)

Faw*_*waz 5

您需要将计时器保持在状态,以便在组件的生命周期中保持活动状态:

componentDidMount(){
  this.fetchNowPlaying();
  const timer = setInterval(this.fetchNowPlaying, 30000);
  this.setState({ timer });
}

componentWillUnMount() {
  clearInterval(this.state.timer);
}
Run Code Online (Sandbox Code Playgroud)

这里参考.