如何正确使用导航

时间:2018-11-12 13:07:30

标签: react-native

我正在通过导航创建应用。我进行导航的组件具有以下代码:

const AppNavigator = createStackNavigator({
    Articles: { screen: ArticlesScreen },
    Profile: { screen: ProfileScreen},
    ModalProfile: { screen: ModalProfile},
},
{
    cardStyle: { backgroundColor: '#fff' }
 });

 export default AppNavigator;

ArticlesScreen将首先安装,调用componentDidMount(),当我在文章屏幕(带有按钮)中调用this.props.navigation.navigate('Profile')时,导航到我的“个人资料”屏幕,并调用componentDidMount()功能我的简历。调用this.props.navigation.navigate('Articles')时,导航将转到ArticlesScreen,而不是调用componentDidMount()。但是,当再次调用this.props.navigation.navigate('Profile')时,我的个人资料的componentDidMount()函数将执行,这会产生一些问题。

在简历中,为什么当我调用ProfileScreen时页面被零加载,而我的ArticlesScreen却没有?我该如何解决?

1 个答案:

答案 0 :(得分:1)

componentDidMount()仅在安装组件时被调用。如果该组件已经在导航历史记录中,则当您导航回该组件时,不会再次安装它。因此,componentDidMount()不会被调用。

当您导航回到先前安装的组件时,将在您刚刚导航到的组件之后卸载的所有组件都将被卸载。这意味着,当您从Articles导航到Profile时,Profile被卸载。这就是为什么回到Profile会再次触发componentDidMount()的原因。

了解Navigation lifecycle将在这里为您提供帮助。

Example scenario使其更加清晰。

  

考虑一个带有屏幕A和B的堆栈导航器。导航到A后,将调用其componentDidMount。推入B时,它的componentDidMount也被调用,但是A保持安装在堆栈上,因此它的componentWillUnmount不被调用。

     

从B返回到A时,将调用B的componentWillUnmount,但是A的componentDidMount并不是因为A始终保持挂载状态。