繁体   English   中英

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

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

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

这是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网页,我仍然得到我的日志里面的间隔componentDidMount我Guide.js,甚至在该网页上回去,它运行componentDidMount并再次运行我的日志,这意味着interval再次运行,我想要做的是在导航至另一个页面之后或同时,我想破坏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

暂无
暂无

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

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