首页 > 解决方案 > ComponentDidMount 在一个屏幕上工作,但在另一个屏幕上不起作用 - React-Native

问题描述

我读了一下,似乎 ComponentDidMount 似乎没有激活的原因是因为它已经在堆栈导航器上。为此,我们必须将 addListener 与“didFocus”一起使用。

假设我有 3 个屏幕 A、B、C。我不明白为什么当我的应用程序加载到屏幕 B 上时,componentDidMount 在屏幕 B 上从 C->B 隐式工作(我不需要'didFocus'),但不能从 A->B 工作

ComponentDidMount() 
{
   //ComponentDidMount Located in Screen B

   execute code1.  //works from C->B, Does not work from A->B

   this.props.navigation.addListener('didFocus'{
      execute code2.    //Works for both
   })
}

堆栈导航器看起来像这样

createStackNavigator({
FriendsArea: {
    screen:B,
    navigationOptions:{
      header:null
    }
  },
  HostArea: {
    screen:C,
    navigigationOptions:{
      header:null
    }
  },
  Profile: {
    screen:A,
    navigationOptions:{
      header:null
    }
  },
})

有人可以帮忙吗?如果有需要我可以再澄清一些,谢谢。

标签: reactjsreact-native

解决方案


顺序在堆栈导航器中很重要,您应该像这样安排堆栈:

createStackNavigator({
FriendsArea: {
  screen:A,
    navigationOptions:{
      header:null
    }
  },
  HostArea: {
    screen:B,
    navigigationOptions:{
      header:null
    }
  },
  Profile: {
    screen:C,
    navigationOptions:{
      header:null
    }
  },
})

A = 第一页,B = A 之后的下一页,C = B 之后的下一页

您的问题发生是因为 B 组件在创建 A 组件时已经调用了 componentDidMount 方法,因此您必须调用 didFocus 侦听器,该侦听器通常用于在我们从其他页面导航回来时执行代码。


推荐阅读