除了一个实例外,setInterval始终如我所期望的那样。如果用户通过单击“主页按钮”离开应用程序并通过单击图标(而不是从概述中选择)重新启动应用程序,则旧的setInterval尚未停止。它重新开始,现在运行2个setIntervals。如果我重复这个过程,用户可以同时运行数百个间隔,它会继续下去。
如何防止这种情况?我想在那时只运行一个seInterval实例。
这是我的代码:
import React, { Component } from 'react';
import {
AsyncStorage,
Text,
View,
AppState,
} from 'react-native';
import timer from'react-native-timer';
class Code_temp extends Component {
redirect(routeName){
this.props.navigator.push({
name: routeName
});
}
constructor(props){
super(props);
this.state = {
appState: AppState.currentState,
};
}
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
this.setState({showMsg: true}, () => timer.setInterval(
this, 'hideMsg', () =>{
console.log( 1 );
}, 1000
));
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange);
}
_handleAppStateChange = (nextAppState) => {
if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
}
this.setState({appState: nextAppState});
};
componentWillMount() {
}
render() {
return (
<View>
<Text>
Test
</Text>
</View>
);
}
}
export default Code_temp
答案 0 :(得分:0)
那是因为你卸载组件时没有清除setInterval,也从setinterval参数中删除'this'
componentDidMount() {
timer.clearInterval('hideMsg');
AppState.addEventListener('change', this._handleAppStateChange);
this.setState({showMsg: true}, () => timer.setInterval(
'hideMsg', () =>{
console.log( 1 );
}, 1000
));
}
componentWillUnmount() {
timer.clearInterval('hideMsg');
};