简体   繁体   中英

React Navigation - goBack() is automatically invoked for stack navigator screen

I have 3 stack navigator screens (Home, Item List, Item Detail -> same order) inside drawer navigator and all three screens are hooked up to redux store with connect() helper.

When I do navigate('ItemDetail') from ItemList, it navigates to the screen and immediately comes back to ItemList screen. I am not sure why.

Following is my navigation structure -

const AppStack = createStackNavigator(
  {
    Home: {
      screen: HomeScreen
    },
    ItemList: {
      screen: ItemListScreen
    },
    ItemDetail: {
      screen: ItemDetailScreen
    }
  },
  {
    initialRouteName: 'Home'
  }
);

const DrawerNav = createDrawerNavigator(
  {
    DrawerApp: AppStack
  },
  {
    drawerPosition: 'right'
  }
);

const SwitchStack = createSwitchNavigator(
  {
    Loading: Loading,
    Auth: AuthStack,
    App: DrawerNav
  },
  {
    initialRouteName: 'Loading'
  }
);

This is how my each navigation screen component looks -

export class ProviderListScreen extends Component {
  render() {
    const { navigation } = this.props;
    // ItemList is hooked up to Redux via connect() helper
    return <ItemList navigation={navigation} />; 
  }

On my ItemDetail component, I get the Item data through route params from ItemList screen and I also dispatch an action (To reset some part of the store state) in component did mount. As soon as I do that, previous screen (ItemList) is automatically rendered.

Inside item detail, I make API call to create booking for that item and the booking object is managed by redux. Once I land on the ItemDetail, I reset the booking object for new booking data.

Here is the snippet of ItemDetail's componentDidMount -

componentDidMount() {
    this.props.resetItembooking();
  }

I am not sure what is causing this behaviour. If I remove the ItemList screen and jump directly to ItemDetail screen from HomeScreen, this issue does not occur.

Any help is appreciated.

I had the exact same problem however I tried the answer given in the original post comments sections given by Awadhoot but this did not work for me.

For anyone still trying to solve this issue, ensure you do not have any recurring intervals setup. Therefore you should always clear intervals before navigating away:

clearInterval(this.intervalId);

In react-navigation 5 you can use the useIsFocused hook for that:

import { useIsFocused } from '@react-navigation/native';

// ...

function Profile() {
  const isFocused = useIsFocused();

  return <Text>{isFocused ? 'focused' : 'unfocused'}</Text>;
}

From the docs: https://reactnavigation.org/docs/use-is-focused/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM