【问题标题】:ComponentDidMount work from one screen but does not work from the other - React-NativeComponentDidMount 在一个屏幕上工作,但在另一个屏幕上不起作用 - React-Native
【发布时间】:2020-11-25 04:49:55
【问题描述】:

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

假设我有 3 个屏幕 A、B、C。我不明白为什么当我的应用程序加载到屏幕 B 上时,componentDidMount 从 C->B 在屏幕 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
    }
  },
})

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

【问题讨论】:

  • 能贴出stack navigator的创建吗?
  • 屏幕A、B、C是否正常?
  • @fxbayuanggara 我包含了堆栈导航器
  • @KushalDesai 屏幕顺序请看添加的代码。
  • 有人知道吗?

标签: reactjs react-native


【解决方案1】:

堆栈导航器中的顺序是重要的,你应该像这样排列堆栈:

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 侦听器,该侦听器通常用于在我们从其他页面导航返回时执行代码。

【讨论】:

  • 不幸的是,这仍然对我不起作用。尽管页面是有序的,但从个人资料导航到 FriendsArea 仍然不需要“didFocus”。我希望它需要'didFocus'
猜你喜欢
  • 2019-04-08
  • 1970-01-01
  • 1970-01-01
  • 2018-12-25
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 2020-11-14
  • 1970-01-01
相关资源
最近更新 更多