导航到不同的屏幕不会调用任何功能

问题描述 投票:1回答:3

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

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

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

当我在堆栈A并且将首次导航到堆栈B时,堆栈B将读取componentDidMount(),在这里我将设置一个状态(连接到rest服务器以从数据库调用数据)。

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

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

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

react-native react-navigation
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;

0
投票

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

它只是为您存储所有内容,以便当您向后导航时,无论您离开屏幕的状态如何,所有内容都存在。

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

所以当你回来时它什么都不会做。

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

所以对于你的情况,

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

像这样,

假设你在screenB中,并想调用一个方法methodSuperCool=()=>{...},它位于你导航到当前屏幕的screenA中。

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

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

导航到屏幕之前现在进入屏幕A调用此,

 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

0
投票

从堆栈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以获得完整答案。

© www.soinside.com 2019 - 2024. All rights reserved.