以下代码为我解决了上述问题。
AppNavigation.js
export default function AppNavigation() {
return (
<NavigationContainer
fallback={<FullScreenLoadingIndicator visible />}
onReady={Navigation.goToInitialRoute}
ref={navigationRef}
linking={linkingConfig}
documentTitle={{
enabled: false,
}}
>
<AppNavigator authenticated={this.props.authenticated} />
</NavigationContainer>
);
}
NavigationService.js
export const navigationRef = createNavigationContainerRef();
let initialRoute = null;
function navigate(route) {
console.log(`trying to navigate to ${route}`);
if (navigationRef.isReady()) {
console.log(`navigationRef ready, navigating to ${route}`);
// Some business logic, but basically just this
navigationRef.current.dispatch(someAction);
} else {
// Navigation container not yet loaded, set initial route.
console.log(`navigation not ready, setting initialRoute: ${route}`);
initialRoute = route;
}
}
function goToInitialRoute() {
console.log(`initial route: ${initialRoute}`);
if (initialRoute) {
console.log('going to initial route');
navigate(initialRoute);
}
}
export default {
navigate,
goToInitialRoute,
};
您可以按照
官方文档中明确推荐的方式使用
onReady
的 NavigationContainer
属性。
导航容器及其所有子容器第一次完成挂载后调用的函数。您可以将其用于:
- 确保参考可用。
我们可以使用它并设置一个道具
isReady
并将其传递给 Router
。
const [isReady, setIsReady] = useState(false)
<NavigationContainer onReady={() => setIsReady(true)} ref={navigationRef}>
<Router ready={isReady} />
<StatusBar style="auto" />
</NavigationContainer>
这是处理每个导航操作的方法(使用 TypeScript):
ReactNavigationHelper:
const actionQueue: (
| NavigationAction
| ((state: NavigationState) => NavigationAction)
)[] = [];
function dispatch(
action: NavigationAction | ((state: NavigationState) => NavigationAction)
) {
if (navigationRef.isReady()) {
navigationRef.dispatch(action);
} else {
console.warn("Navigation is not ready. Adding action to queue.");
actionQueue.push(action);
}
}
function navigate(
name: string,
params?: Record<string, any>,
key?: string,
path?: string,
merge?: boolean
) {
dispatch(
CommonActions.navigate({
name,
params,
key,
path,
merge
})
);
}
function handleNavigationContainerReady() {
console.debug("Navigation is ready");
// Dispatch all the queued navigation actions
while (actionQueue.length > 0) {
const action = actionQueue.shift();
if (action) {
console.debug("Dispatching queued action", action);
dispatch(action);
}
}
}
并且在您的
NavigationContainer
中,您应该处理就绪状态更改:
<NavigationContainer onReady={handleNavigationContainerReady} ref={navigationRef}>
...
</NavigationContainer>