首页 > 解决方案 > 如何解决 ReactNative 反应导航中的错误?

问题描述

我不断收到此错误消息,尤其是当我将钩子应用于会话管理的条件时。

找不到导航对象。您的组件是否在导航器的屏幕内?

你能帮我解决这个问题吗?

这是我的代码。我不知道我在哪里做错了。

导航.jsx

const Navigation = () => {
  const { user, isLoading } = useHook();
        if (isLoading) {
        return <SplashScreen />;
    }
    return (
        <>
        <StatusBar barStyle="default" />
            <Stack.Navigator>
                {user ? (
                    <>
            <Stack.Screen name={routes.Deliveries} 
            options={{
              headerShown: false,
            }}>
              {() => <MainTab />}
            </Stack.Screen>
                </>
                ) : (
                <>
                    <Stack.Screen name={routes.Login} component={LoginScreen} 
          options={{
            headerShown: false,
          }}/>
          </>
                )}
            </Stack.Navigator>
        </>
    );
}

export default Navigation;

应用程序.js

import React, { createContext } from 'react';
import { StyleSheet, SafeAreaView, } from 'react-native';
import { ThemeProvider } from 'styled-components';
import theme from 'utils/ThemeStyle';
import Navigation from './src/components/navigation';
import { NavigationContainer } from '@react-navigation/native';
import GlobalHook from './src/globalHooks';

export const GlobalContext = createContext({});


export default function App() {
    const globalData = GlobalHook();
    return (
        <SafeAreaView style={styles.container}>
            <NavigationContainer>
                <GlobalContext.Provider value={globalData}>
                    <ThemeProvider theme={theme}>
                        <Navigation />
                    </ThemeProvider>
                </GlobalContext.Provider>
            </NavigationContainer>
        </SafeAreaView>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
});

错误在我声明我的钩子对象后立即开始。

标签: javascriptreact-nativeexporeact-navigation

解决方案


尝试像这样使用NavigationContainer包装您的应用程序

import { NavigationContainer } from '@react-navigation/native';
const Navigation = () => {
  const { user, isLoading } = useHook();
        if (isLoading) {
        return <SplashScreen />;
    }
    return (
        <>
        <StatusBar barStyle="default" />
          <NavigationContainer>
            <Stack.Navigator>
                {user ? (
                    <>
            <Stack.Screen name={routes.Deliveries} 
            options={{
              headerShown: false,
            }}>
              {() => <MainTab />}
            </Stack.Screen>
                </>
                ) : (
                <>
                    <Stack.Screen name={routes.Login} component={LoginScreen} 
          options={{
            headerShown: false,
          }}/>
          </>
                )}
            </Stack.Navigator>
           </NavigationContainer>
        </>
    );
}

export default Navigation;

如果没有安装

yarn add @react-navigation/native

推荐阅读