简体   繁体   English

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

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

I'm using react-native, when I try to navigate to another page using StackNavigator the previous page is running on the background 我正在使用react-native,当我尝试使用StackNavigator导航到另一个页面时,上一个页面在后台运行

This is App.js 这是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' });

And I have a Guid.js like this 我有一个像这样的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>
  )
}

The problem is, even I navigate to the main page, I still getting the interval that I log inside the componentDidMount of my Guide.js, and even going back on that page, it runs the componentDidMount and run again my log, that means the interval is running again, what I want to do is after or while navigating to another page, I want to destroy the Guide.js, the page where I came from, and I have a page where I run WebView I wan't to do the same thing for that page, how can I do that? 问题是,即使我浏览到main网页,我仍然得到我的日志里面的间隔componentDidMount我Guide.js,甚至在该网页上回去,它运行componentDidMount并再次运行我的日志,这意味着interval再次运行,我想要做的是在导航至另一个页面之后或同时,我想破坏Guide.js,即我来自的页面,而我有一个页面在其中我不想执行的WebView该页面的相同内容,我该怎么做?

Once timers are set, they runs asynchronously, you have to remove the timer if it's no longer needed when you leave the screen, like so: 设置好计时器后,它们将异步运行,如果您离开屏幕时不再需要该计时器,则必须删除它,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM