javascript - 警告 : Can only update a mounted or mounting component while calling api inside setInterval (React Native)

标签 javascript android ios reactjs react-native

我一直在开发一个应用程序,我需要每 30 秒调用一次 API 并将响应设置为某种状态。我在 setInterval 中进行。我有一个在应用程序的所有屏幕上呈现的组件。 (setInterval 所在的同一组件)。一切似乎都正常,但是当我按下后退按钮转到上一个屏幕时,我收到此警告“未安装组件上的 setState”。请记住,组件也会在此屏幕中再次安装。废话不多说了,让我把代码放在这里。

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});
    ........
    });
  }

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

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

React Native version - 0.45.1

最佳答案

您需要保持定时器处于状态,以便在组件的生命周期内保持其 Activity 状态:

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

componentWillUnMount() {
  clearInterval(this.state.timer);
}

引用自here .

关于javascript - 警告 : Can only update a mounted or mounting component while calling api inside setInterval (React Native),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45753204/

相关文章:

javascript - 隐藏用户地址栏中的主题标签

javascript - 在 React 中合并两个状态数组

java - 通过 HDMI 或 USB 连接在 android 上接收音频和视频

java - 寻找 android Facebook SDK 示例

android - 通过intent-Android传递int数组

ios - 在 iOS 模拟器上模拟 MFMailComposeViewController。只需要显示 Composer

javascript - 每当您返回使用 javascript 或 jsf 的页面时,如何在 jsp 页面上维护复选框状态,而不将其存储到数据库中

javascript - XPCOM 中的 popen 等价物?

ios - 本地安装的iOS应用程序有有效期限吗?

ios - 在同一 Action 中弹出和推送 View Controller