BlackWolf BlackWolf - 5 months ago 35
React JSX Question

Reuse screen in React Navigation

I'm new to React Native and trying to set up a navigation between two screens (or pages) using react-navigation package. I'm using a

StackNavigator
right now.

The problem I am facing is that there seems to be no way to navigate back to a previous screen. All I can do is call
navigate()
. If, for example, I want to navigate from
Home
to
FRW
and back to
Home
, it seems this will leave me with two instances of
Home
on the stack that are executed in parallel (one of which can't be seen). My code is something like this:

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 looks similar to HomeScreen.js (and contains
.navigate("Home")
)


The result of this code is, after navigating to FRW and back, that the geolocation callback is executed twice with different watchIDs. Which makes me believe the HomeScreen is actually on the navigation stack twice.

Answer Source

On your FRWScreen you should use this.props.navigation.goBack(null) instead. See https://reactnavigation.org/docs/navigators/navigation-prop#goBack-Close-the-active-screen-and-move-back.