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

问题描述 投票:0回答:2

我正在使用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页面,我仍然得到我登录我的Guide.js的componentDidMount的间隔,甚至回到该页面,它运行componentDidMount并再次运行我的日志,这意味着间隔再次运行,我想要做的是在导航到另一个页面之后,我想要销毁Guide.js,我来自的页面,我有一个页面,我运行WebView我不想做该页面的内容相同,我该怎么做?

javascript react-native stack-navigator
2个回答
1
投票

一旦设置了定时器,它们就会异步运行,如果在离开屏幕时不再需要定时器,则必须将其移除,如下所示:

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);
    }
}

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.