You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native Drawer导航报错:NAVIGATE动作未被处理问题排查

抽屉导航跳转错误的问题分析与修复

问题根源

  1. 未启用NavigationContainer
    代码里的<NavigationContainer>被注释掉了,这是React Navigation的核心根容器,所有导航组件必须被它包裹才能建立导航上下文,没有它的话,导航功能完全无法正常工作。

  2. 错误在App组件中调用useNavigation
    useNavigation钩子只能在NavigationContainer内部的组件中使用,App组件是整个应用的外层组件,根本获取不到有效的导航上下文,这里拿到的navigation对象是无效的,调用navigate必然报错。

  3. 导航跳转依赖了错误的navigation对象
    在NotificationsScreen的headerLeft按钮里,你用了App组件中获取的无效navigation,正确的做法是使用屏幕自身接收到的navigation prop。

修正后的完整代码

import React from 'react';
import { Button, View } from 'react-native';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { NavigationContainer } from '@react-navigation/native';
import AntDesign from '@expo/vector-icons/AntDesign';

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button
        onPress={() => navigation.openDrawer()}
        title="Open drawer"
      />
      <Button
        onPress={() => navigation.closeDrawer()}
        title="Close drawer"
      />
    </View>
  );
}

function NotificationsScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button onPress={() => navigation.goBack()} title="Go back home" />
    </View>
  );
}

const Drawer = createDrawerNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Drawer.Navigator initialRouteName="Home" backBehavior="history">
        <Drawer.Screen name="Home" component={HomeScreen} />
        <Drawer.Screen 
          name="Notifications" 
          component={NotificationsScreen}
          options={({ navigation }) => ({
            title: "Settings",
            headerLeft: () => (
              <AntDesign 
                name="arrowleft" 
                size={30} 
                color="black"
                onPress={() => navigation.navigate('Home')}
              />
            ),  
          })}
        />
      </Drawer.Navigator>
    </NavigationContainer>
  );
}

关键修正点说明

  • 取消了NavigationContainer的注释,将整个Drawer.Navigator包裹在其中。
  • 删除了App组件中错误的useNavigation调用。
  • 在NotificationsScreen的options中,通过({ navigation })获取当前屏幕的导航对象,用于headerLeft的跳转逻辑。

内容的提问来源于stack exchange,提问作者SIMON SERWADDA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 21:46:06