使用 StackNavigator 导航到另一个页面时销毁当前页面并停止上一页上的所有 运行 进程

destroy the current page when navigating to another page using StackNavigator and stop all running process on previous page

我正在使用 react-native,当我尝试使用 StackNavigator 导航到另一个页面时,前一页在背景上 运行ning

这是App.js

import Login from './app/component/Login';
import Menu from './app/component/Menu';
import Guide from './app/component/additions/Guide';
import { StackNavigator } from 'react-navigation';

const Navigator = StackNavigator({
  login: {screen: Login},
  main: {screen: Menu},
  guide: {screen: Guide},
},{ headerMode: 'none' });

我有一个 Guid.js 这样的

componentDidMount() {
  setInterval(() => {
    console.log('I do not leak');
  }, 1000);
}

render() {
  const {navigate} = this.props.navigation;
  return(
    <TouchableOpacity onPress={() => navigate('main')}>
      <Text> navigate to main </Text>
    </TouchableOpacity>
  )
}

问题是,即使我导航到 main 页面,我仍然得到我在 Guide.js 的 componentDidMount 中登录的时间间隔,甚至返回那个页面,它 运行s componentDidMount 和 运行 又是我的日志,这意味着间隔又是 运行ning,我想做的是在导航到另一个之后或导航到另一个页面,我想销毁 Guide.js,我来自的页面,我有一个页面 运行 WebView 我不想对那个页面做同样的事情,我该怎么做?

设置定时器后,它们将异步运行,如果您离开屏幕时不再需要定时器,则必须将其删除,如下所示:

constructor(props) {
    this.timerID = null;
}

componentDidMount() {
    this.timerID = setInterval(() => {
        console.log('I do not leak');
    }, 1000);
}

/**
 * Frees up timer if it is set.
 */
componentWillUnmount() {
    if (this.timerID != null) {
        clearInterval(this.timerID);
    }
}

您可以使用新的 React-native Lazy 只在需要时加载组件 API,这里有一些关于如何使用的文档:https://reactjs.org/docs/code-splitting.html