简体   繁体   中英

How can I fix the "undefined is not an object (evaluating 'navigation.navigate')"?

So, here is the Navigation Container I've created:

<NavigationContainer>
        <Stack.Navigator
          screenOptions={{
            headerShown: false
          }}
        >
          <Stack.Screen name="Home" component={HomeScreen} />
          <Stack.Screen name="Music" component={MusicScreen} />
          <Stack.Screen name="Profile" component={ProfileScreen} />
        </Stack.Navigator>
      </NavigationContainer>

But I don't need to button be unique on each screen, there will be 3 buttons which will display at all screens. So here is my map function where I map through all of my buttons:

{tabs.map(({ icon, line }, index) => (
                <View key={ index }>
                  <Tab 
                    {...{ index, transition, active }}
                    onPress={() => {
                      active.setValue(index);

                      if (index == 0) {
                        navigation.navigate('Music')
                      } else if (index == 1) {
                        navigation.navigate('Home')
                      } else if (index == 2) {
                        navigation.navigate('Profile')
                      }
                    }}
                  >
                    {icon}
                  </Tab>
                  <View style={styles.blueLineContainerBack}>
                    <LineWrapper
                      {...{activeTransition, active, line, index}}
                    />
                  </View>
                </View>
              ))}

While I'm pressing at a button I'm getting undefined is not an object (evaluating 'navigation.navigate') error. How can I fix that?

It's important to note that navigation is only defined within the screens components. Within your onPress function, call the useNavigation hook to have access to navigation. Something like this should work:

const navigation = useNavigation();

And you need to import it from React Navigation as such:

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

If you are in one of 'Screens' that you defined (Home, Profile, Music) you, the React-Navigation library passes the 'navigation' prop into them. So you should use it like below:

props.navigation.navigate('Music');

If that fails too, you can use react navigation Hooks to access the navigation object like this:

import { useNavigation } from '@react-navigation/native';
const MyComponent = () => {
  const navigation = useNavigation();
  ...
  return(
    ...
    <Button title="Go to music" onPress={() => { navigation.navigate('Music'); }} />
  );
};
export default MyComponent;

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