11
votes

I have react-navigation setup with redux. My app consists of a parent TabBarNavigator with a login and content screen. The content Screen is itself a Stack Navigator that contains the main nav for the app. All other aspects of the redux and navigators work as expected, but the default back button on the StackNavigator also triggers it's parent TabBarNavigator to go back.

Is this expected behavior? I notice that if I define headerLeft in navigationOptions like this, it works as expected:

static navigationOptions = ({ navigation }) => {
    return {
      headerLeft: (
        <Button transparent onPress={() => { navigation.goBack(); }}><Text>Back</Text></Button>
      )
    };
  };

Cam anyone explain what causes this? Is there a way to make the default stackNavigator back button work with redux?

3
did you manage to get around this problem without defining the headerLeft? - zunder
For my understanding the dispatch action with type 'Navigation/BACK' is missing a key if no headerLeft is specified. I guess it is missing the appropriate navigation object for that. - zunder
I solved this by using props.navigation.goBack(null). It's a bit handwavey, but this is what tipped me off to it: reactnavigation.org/docs/navigators/navigation-prop - mienaikoe
same situation! props.navigation.goBack(null) is not working for me. I would like to find a clean solution to use in the reducer. - Julien Malige

3 Answers

1
votes

Maybe dispatching an action will work better:

    onPress={() => {
      navigation.dispatch(NavigationActions.navigate({
        routeName: '<screen name here>'
      }));
    }}
1
votes

You can do one thing on onPress event, before call the goBack() you have to dispatch your action for that particular redux:

static navigationOptions = ({ navigation }) => {
return {
  headerLeft: (
    <Button 
        transparent 
        onPress={() => { 
          <ACTION_DISPATCH>
          navigation.goBack(); 
        }}>
        <Text>Back</Text>
   </Button>
  )
};};
0
votes

In my case the issue was a little more complex because I use the react Navigation Redux Integration.

My back action is well a dispatch of a "back" action but, in my reducer, I missed the second parameter of the getStateForAction method (the state).

getStateForAction(action, state)

https://reactnavigation.org/docs/routers/api#getStateForAction-action-state

So, in my navigation redux, it works with this back reducer:

export const back = (state) => AppNavigator.router.getStateForAction(NavigationActions.back(), state)

With this back action, a back from a nested navigator is not reseting the main navigator.