反应导航:“导航”对象尚未初始化

时间:2020-02-18 08:06:25

标签: react-native react-navigation

我正在通过https://reactnavigation.org/docs/en/upgrading-from-4.x.htmlhttps://reactnavigation.org/docs/en/compatibility.html将React Navigation库从4.xx升级到5。

我遇到错误:

NavigationDebug Error:  Error: The 'navigation' object hasn't been initialized yet. This might happen if you don't have a navigator mounted, or if the navigator hasn't finished mounting. You can ensure that all navigators have mounted after the callback to 'useEffect' is called in your root component. See https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html#handling-initialization for more details.
    at dispatch (BaseNavigationContainer.tsx:202)
    at Object.acc.<computed> [as navigate] (BaseNavigationContainer.tsx:245)
    at Object.navigate (NavigationService.ts:20)
    at SplashScreen.redirectUser (splash-screen.tsx:234)
    at SplashScreen.proxiedMethod (createPrototypeProxy.js:44)
    at _callee2$ (splash-screen.tsx:298)
    at tryCatch (runtime.js:45)
    at Generator.invoke [as _invoke] (runtime.js:271)
    at Generator.prototype.<computed> [as next] (runtime.js:97)
    at tryCatch (runtime.js:45)

在创建NavigationService(https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html)时。

index.js

let Init = ((props) => {

    enableScreens();

    React.useEffect(() => {
        isMountedRef.current = true;

        return () => isMountedRef.current = false;
    }, [])

    return (
        <NavigationContainer ref={navigationServiceRef}>
            <Provider {...stores}>
                    <App {...props}/>
            </Provider>
        </NavigationContainer>
    );
})

AppRegistry.registerComponent(appName, () => Init);

NavigationService

import { NavigationActions, StackActions } from '@react-navigation/compat';

import React from 'react';

export const isMountedRef = React.createRef();

export const navigationServiceRef = React.createRef();

export function navigate(name, params) {
    if (isMountedRef.current && navigationServiceRef.current) {
        console.log("Navigation Should happen")
        try {
            navigationServiceRef.current.navigate("App", params);
        }catch(e){
            console.log("NavigationDebug Error: ", e)
        }
    } else {

    }
}

export default {
    navigate
};

1 个答案:

答案 0 :(得分:0)

“ ...创建NavigationService时” -您确定那是发生错误的时间吗?您的控制台日志是否显示"Navigation Should happen"

也许在其他地方您有一个“导航”调用,该调用在上面显示的逻辑之前执行。

your link - navigating without nav prop中,建议:

“导入RootNavigation” “ RootNavigation.navigate(...)”

也就是说,在导航器准备就绪之前可能会调用“导航”的任何位置,都将navigate替换为RootNavigation.navigate。 (RootNavigation是您的模块,其中包含有问题的代码。有关更多详细信息,请参见链接。)