Home > Software design >  React Native, reactnavigation, how do I goBack() to the previous screen, not the first screen, using
React Native, reactnavigation, how do I goBack() to the previous screen, not the first screen, using

Time:10-25

Here's a demo of my problem: https://snack.expo.dev/xtklvo6eM

I want to go from ScreenOne -> ScreenTwo -> ScreenThree -> goBack() to ScreenTwo....

But calling navigation.goBack() on ScreenThree takes me back to ScreenOne, not ScreenTwo.

Can someone tell me why this is?

import * as React from 'react';
import { Button, View } from 'react-native';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { NavigationContainer } from '@react-navigation/native';

function ScreenOne({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button
        onPress={() => navigation.navigate('ScreenTwo')}
        title="Go to screen two"
      />
    </View>
  );
}

function ScreenTwo({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button onPress={() => navigation.navigate('ScreenThree')} title="Go to screen three" />
    </View>
  );
}

function ScreenThree({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button onPress={() => navigation.goBack()} title="Try to go back to screen two.." />
    </View>
  );
}

const Drawer = createDrawerNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Drawer.Navigator initialRouteName="ScreenOne">
        <Drawer.Screen name="ScreenOne" component={ScreenOne} />
        <Drawer.Screen name="ScreenTwo" component={ScreenTwo} />
        <Drawer.Screen name="ScreenThree" component={ScreenThree} />
      </Drawer.Navigator>
    </NavigationContainer>
  );
}

CodePudding user response:

backBehavior="history"

https://reactnavigation.org/docs/drawer-navigator#backbehavior

  • Related