React Native StackNavigator 在重新进入时消失

React Native StackNavigator disappearing on re-entry

我们在 React Native 应用程序中遇到了一个非常奇怪的反应导航场景,该场景仅在 Android 上观察到(在模拟器和物理设备上 AND 用于调试版本和发布版本),但它在 iOS.

上运行良好

上下文

我们有一个现有的本机应用程序,并决定在 React Native 中实现一些新屏幕作为实验,看看它是否有益于我们的开发生命周期。

我们的本机应用程序有一个侧边栏菜单,我们添加了一个新菜单项,当 selected 时,将用户带到 React Native 部分。他们当然可以随时返回,然后返回到 React Native 部分。

观察到的问题(只发生在 Android)

我们已经确定它与 react-navigation 库有关,但我们不知道我们做错了什么。

首次加载应用程序时,用户可以 select 新菜单项,React Native 应用程序加载正常,显示其初始路由页面并且 StackNavigator 工作正常。

如果用户 return 转到本机部分(通过后退键,或通过 select 从侧边栏菜单中选择不同的选项)然后选择return 到 React Native 部分,然后 StackNavigator 部分不显示。 渲染 StackNavigator 之外的其他 React 组件。我们知道它安装了包含的组件,因为其中一些组件正在调用 API 并且我们看到正在查询这些端点。它只是不呈现。

在模拟器中重新加载将再次正确呈现应用程序,直到我们导航出 React Native 然后 return。

奇怪: 如果我们打开远程 JS 调试,突然一切正常。

所以我们的问题是:

任何人都可以发现我们在使用 StackNavigator 时可能遗漏了什么,这导致它无法正确呈现吗?再一次:当 JS 调试器打开时它工作正常,让我们认为它不是一个逻辑项,但也许是一个时序条件,或者一些微妙的配置?或者我们应该放弃 react-navigation 并转到不同的导航库?

问题的简单再现

我们的package.json是:

{
  "dependencies": {
    "react": "16.0.0",
    "react-native": "0.50.4",
    "react-navigation": "1.5.2"
  }
}

我们的 React Native 入口页面(index.js)是:

import * as React from 'react';
import { AppRegistry, Text, View } from 'react-native';
import { StackNavigator } from 'react-navigation';
import TestPage from './TestPage';

AppRegistry.registerComponent('MyApp', () => MyApp);

class MyApp extends React.Component {
  public render() {
    return (
      <View style={{flex:1}}>
        <Text>'This text always shows up fine on Android, even on reentry to React application'</Text>
        <AccountNavigator />
      </View>
    );
  }
}

const AccountNavigator = StackNavigator(
  {
    FirstPage: {
      screen: TestPage,
      navigationOptions: ({ navigation }) => ({
        title: 'Test View'
      })
  },
  {
    initialRouteName: 'FirstPage'
  }
);

简单的测试页(TestPage.js)就是:

import * as React from 'react';
import { Text, View } from 'react-native';

export default class TestPage extends React.Component {
  render() {
    return (
      <View style={{flex:1, alignItems: 'center', justifyContent: 'center'}}>
        <Text>'If you can read this, then the app is on first load. But return to the native portion and then try to come back to React Native and you will not see me.'</Text>
      </View>
    );
  }
}

原来是布局设置问题。在我们的本机代码中,在我们的 React Activity 布局 XML 中,我们有:

 <com.facebook.react.ReactRootView
    android:id="@+id/ReactRootView
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

问题出在 "wrap_content" 的高度,这导致它将 StackNavigator() 渲染为 1 像素高。不知道为什么它总是只发生在 re-entry 而不是第一次,也不知道为什么 JS 调试器会导致问题消失。

将 layout_height 更改为 "match_parent" 完全解决了这个问题。