在 React Navigation 中重用屏幕

Reuse screen in React Navigation

我是 React Native 的新手,正在尝试使用 react-navigation 包在两个屏幕(或页面)之间设置导航。我现在正在使用 StackNavigator

我面临的问题是似乎无法导航回上一个屏幕。我能做的就是打电话navigate()。例如,如果我想从 Home 导航到 FRW 并返回到 Home,这似乎会让我在堆栈上留下两个 Home 的实例,它们是并行执行(其中一个看不到)。我的代码是这样的:

app.js

import React, { Component } from 'react';
import { AppRegistry } from 'react-native';

import { StackNavigator } from 'react-navigation';

import HomeScreen from './views/HomeScreen.js'
import FRWScreen from './views/FRWScreen.js'

  const MainNavigator = StackNavigator({
    FRW: { screen: FRWScreen },
    Home: { screen: HomeScreen },
  }, {
    headerMode: 'screen',
    headerVisible: false,
    navigationOptions: {
      header: null
    },
    initialRouteName: "Home"
  });

export default class TestApp extends Component {  
  render() {    
    return (
      <MainNavigator></MainNavigator>
    );
  }
}

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

HomeScreen.js

export default class HomeScreen extends Component {
  static navigationOptions = {
    title: 'Welcome'
  };

  (...)

  onSomeButtonPressed() {
    this.props.navigation.navigate('FRW');
  }

  componentDidMount() {
    if (this.locationWatchID !== undefined) return;

    this.locationWatchID = navigator.geolocation.watchPosition((position) => {
      console.log(this.locationWatchID);
    });
  }

  componentWillUnmount() {
    navigator.geolocation.clearWatch(this.locationWatchID);
  }

render() {
  (...)

    return (
      <View style={styles.container}>
        <MapView ref={ref => { this.map = ref; }} />
        <TouchableHighlight
          style={styles.someButton}
          onPress={this.onSomeButtonPressed.bind(this)}
        >
          <Text>Press Me</Text>
        </TouchableHighlight>
      </View>
    )
  }
}

FRWScreen.js 看起来类似于 HomeScreen.js(并包含 .navigate("Home")

此代码的结果是,在导航到 FRW 并返回后,使用不同的 watchID 执行了两次地理定位回调。这让我相信 HomeScreen 实际上在导航堆栈上出现了两次。

在您的 FRWScreen 上,您应该改用 this.props.navigation.goBack(null)。参见 https://reactnavigation.org/docs/navigators/navigation-prop#goBack-Close-the-active-screen-and-move-back