简体   繁体   中英

undefined is not an object (evaluating 'navigation.navigate') React Native

I'm have a problem in react navigation, error message "undefined is not an object (evaluating 'navigation.navigate')". Error happens when trying to call a screen by a button from another route

Component code:

     export default function Estruturas({ title, display, navigation }) {
      const [estruturas, setEstruturas] = useState([]);
    
      useEffect(() => {
        async function loadEstruturas() {
          const response = await api.get('/produto/api/estrutura');
    
          setEstruturas(response.data);
        }
        loadEstruturas();
      }, []);
    
    
      return (
...
   
          <ProductList>
            {estruturas.map(estrutura => (
              <Item key={estrutura.id} onPress={()=> navigation.navigate('Pedidos')}> 
...

Routes code:

const Tab = createMaterialBottomTabNavigator();
function MyTabs(){
    return(
        <Tab.Navigator
        barStyle={{ backgroundColor: '#694fad' }} 
        initialRouteName='Feed'   
        activeColor='black' 
        >
            <Tab.Screen 
                name="Início"
                component={Dashboard}
                options={{
                    tabBarLabel: 'Início',
                    tabBarIcon: ({ color }) => (
                      <MaterialCommunityIcons name="home"  size={26} />
                    ),
                  }}
            />
            <Tab.Screen 
                name="Pedidos"
                component={Requests}
                options={{
                    tabBarLabel: 'Pedidos',
                    tabBarIcon: ({ color }) => (
                      <MaterialCommunityIcons name="assignment"  size={26} />
                    ),
                  }}
            />
        </Tab.Navigator>)}

export default function Routes() {      
    return (
      <NavigationContainer>
        <MyTabs />
      </NavigationContainer>
    );
  }

I tried with Stack but it gave the same error

Only the direct child of your navigator stack will have access to the navigation prop. I can see that your component Estruturas is not a direct route so it will not get the navigation prop directly inside the function props. There are 2 ways to get this done and fixed.

  • Either use a withNavigation HOC provided by react-navigation v4 or if you are using v5 then use useNavigation hook.
  • OR you need to pass the navigation prop to the component wherever you are calling this component. This can be done as below:-

 export default function Dashboard(props) { return ( <View> <Estruturas navigation={props.navigation} /> </View> ); }

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