【问题标题】:Nagivating to different screen does not call any function导航到不同的屏幕不会调用任何函数
【发布时间】:2023-03-20 08:08:02
【问题描述】:

我正在使用反应导航在我的应用程序中创建一个抽屉。我在导航到不同的屏幕时注意到了这种情况。

假设我的应用中有这个堆栈:

  • 堆栈 A
  • 堆栈 B
  • 堆栈 C

当我在堆栈 A 并且将导航到堆栈 B 第一次进入时,堆栈 B 将读取 componentDidMount() 并且在这里我将设置一个状态(即连接到休息服务器从数据库中调出数据)。

从堆栈 B 中,我也将导航到堆栈 C 第一次进入,并且通过阅读 componentDidMount() 也可以正常工作。然后我对 Stack C 做了一些更改(例如:删除数据),这将影响 Stack B 中的数据。

现在我来自堆栈 C 并导航回堆栈 B(第二次进入),但它不会再读取 componentDidMount()。因此,在我下拉屏幕刷新数据之前,我的数据不会更新。

如何让屏幕每次进入屏幕时都能读取到componentDidMount()

【问题讨论】:

    标签: react-native react-navigation


    【解决方案1】:

    在这种情况下,您需要监听NavigationEvents,因为组件已经挂载,但每次视图获得焦点时都会调用 didFocus。

    这是来自文档的示例代码:

    import React from 'react';
    import { View } from 'react-native';
    import { NavigationEvents } from 'react-navigation';
    
    const MyScreen = () => (
      <View>
        <NavigationEvents
          onWillFocus={payload => console.log('will focus',payload)}
          onDidFocus={payload => console.log('did focus',payload)}
          onWillBlur={payload => console.log('will blur',payload)}
          onDidBlur={payload => console.log('did blur',payload)}
        />
        {/* 
          Your view code
        */}
      </View>
    );
    
    export default MyScreen;
    

    【讨论】:

    • 我阅读了文档,这是唯一的方法。虽然花了一些时间来理解它。谢谢!
    【解决方案2】:

    这就是堆栈导航器所做的,它想再次加载整个屏幕。

    它只是为您存储所有内容,因此当您返回时,无论您离开屏幕的任何状态,所有内容都在那里。

    例如,您在特定屏幕上滚动到一半并导航到其他屏幕, 现在你回来了,你会发现你的屏幕在你离开的地方滚动了一半。

    所以当你回来时它不会做任何事情。

    注意:如果屏幕在过去导航并存在于当前堆栈中,那么再次导航到屏幕将不会调用任何生命周期方法。

    所以对于你的情况,

    您可以将方法引用传递给导航参数。并在导航之前调用它。

    像这样,

    假设您在 screenB 中并想调用位于 screenA 中的方法 methodSuperCool=()=&gt;{...},您从中导航到当前屏幕。

    为此,当您从 screenA 导航到 screenB 时,您必须在 params 中传递方法引用。

    this.props.navigation.navigate('screenB',{methodSuperCool:this.methodSuperCool});
    //this to be write in screenA
    

    现在在 screenB 中,在您导航到 screenA 之前调用它,

     this.props.navigation.state.params.methodSuperCool() // this can also have params if you like to pass
     this.props.navigation.navigate('screenA') // or goBack() method will also work
    

    【讨论】:

    • 感谢您的回答,但我知道这种方法,由于某种原因,我无法使用这种方法,因为我将抽屉(sidemenu)放在另一个文件中,并将其包含在我的应用程序的每个屏幕中。所以当我想导航到其他屏幕时,我无法设置此方法。
    • @Emerald 你可以把这个方法放在屏幕和抽屉里,你可以从屏幕上调用它(抽屉方法)使用参考。
    【解决方案3】:

    从堆栈 C 导航回堆栈 B 不会调用 componentDidMount(),因为在第一次创建堆栈 B 时组件已经挂载。

    当像这样从堆栈 B 导航到堆栈 C 时,您可以重置导航堆栈

    const stackCAction = StackActions.reset({
        index: 0,
        actions: [NavigationActions.navigate({ routeName: 'StackC' })],
    });
    

    调度

    this.props.navigation.dispatch(stackCAction);
    

    注意这样做是不可能的。

    或者,您可以将回调函数从堆栈 B 传递到堆栈 C 以进行刷新。

    查看此link 以获得完整答案。

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 2023-01-11
      • 2022-11-23
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      • 2017-09-26
      相关资源
      最近更新 更多