我一直在开发一个应用程序,我需要每 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/