2

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

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

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

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

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

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

每次进入屏幕时,我应该如何让屏幕能够读取componentDidMount() ?

4

3 回答 3

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;
于 2019-02-21T04:46:25.307 回答
0

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

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

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

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

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

所以对于你的情况,

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

像这样,

假设您在 screenB 中并且想要调用methodSuperCool=()=>{...}驻留在screenA其中的方法,您从中导航到当前屏幕。

为此,当您从 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
于 2019-02-21T04:48:44.137 回答
0

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

你可以做的是在从 Stack B 导航到 Stack C 时重置导航堆栈,就像这样

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

派遣

this.props.navigation.dispatch(stackCAction);

请注意,这样做是不可能的。

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

检查此链接以获得完整答案。

于 2019-02-21T05:32:42.807 回答