React Navigation堆栈clearInterval不工作
App.js示例
const AppNavigator = createStackNavigator({
Home: {
screen: Home,
},
Contact: {
screen: Contact,
}
});
Home.js示例
componentDidMount() {
this.interval = setInterval(this.load, 10000);
}
componentWillUnMount(){
clearInterval(this.interval);
}
当我从家切换到联系人时,间隔仍然有效。请帮帮我。
实际上,正如@ABDELKHALEK所说,当导航到另一个屏幕时,组件不会被卸载。您需要做的是使用react导航事件来清除间隔:
componentDidMount() {
this.interval = setInterval(this.load, 10000);
// This will clear interval when navigating between screens
this._unsubscribe = navigation.addListener('blur', () => {
clearInterval(this.interval)
});
}
componentWillUnMount(){
// call this function to clean navigation listener when unmounting component
this._unsubscribe();
}
请记住,如果您想在每次用户关注此组件时运行间隔,则还需要使用focus
事件。
实际上,我不认为导航到另一个屏幕会卸载组件。
因此,我建议在导航到联系人屏幕时执行以下操作:
import { StackActions, NavigationActions } from 'react-navigation';
const resetAction = StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'Contact' })],
});
this.props.navigation.dispatch(resetAction);