reactjs - 在普通函数中使用 react navigation.navigate - (不允许使用挂钩,即 useNavigation)?
问题描述
我正在尝试将导航到另一个模块中的屏幕的功能并将其导出,但navigation
不起作用。我试过UseNavigation()
但我得到一个错误,即:Unhandled promise rejection: Invariant Violation: Hooks can only be called inside the body of a function component.
有没有办法在正常功能或其他任何功能中使用导航。
import React, { useState, useEffect, useCallback } from "react";
import { AsyncStorage, Alert } from "react-native";
import { useNavigation } from "react-navigation-hooks";
export const startMixGame = async (categoryIsChosen, withTimer) => {
const navigation = useNavigation();
if (categoryIsChosen) {
if (withTimer) {
await AsyncStorage.setItem("useTimer", "true");
navigation.navigate({
routeName: "MixedQuestions",
params: {
categoryId: "1"
}
});
} else if (!withTimer) {
// console.log("withTimer", withTimer);
await AsyncStorage.setItem("useTimer", "false");
navigation.navigate({
routeName: "NoTimerMixedQuestions",
params: {
categoryId: "1"
}
});
}
}
};
谢谢
解决方案
是的,使用单例服务保存对导航的引用,在您的应用程序的根目录中使用 useEffect 保存单例中的引用,这样您就可以在任何地方使用它。像这样的东西:
class NavigationService {
constructor() {
this._navigation = null;
}
set navigation(nav) {
this._navigation = nav;
}
get navigation() {
return this._navigation;
}
}
const navigationService = new NavigationService();
export default navigationService;
并在您的主屏幕/视图中
const HomeScreen = ({navigation}) => {
useEffect(() => {
navigationService.navigation = navigation;
}, [navigation]);
....
现在你可以在任何地方做到这一点
import navigationService from '../services/navigation';
navigationService.navigation.navigate('Screen');
推荐阅读
- python - 在python3中对同时包含字符串和整数的文件进行排序
- xml - 将命名空间添加到 xsd 元素
- html - HTML CSS:仅为内部元素添加边框网格线
- c# - For 循环不执行所有代码 - 没有错误
- c - _headerfile_h 这个名字是什么意思
- postgresql - 如何解决通过cron作业使用pg_dump进行定期备份时生成零字节文件的问题?
- java - Apache-Tika 库是否支持以下 android oreo 设备?
- android - 打开应用程序时 getIntent().getStringExtra() 为空
- javascript - 从托管在 Firebase Hosting 上的页面使用 HTML5 下载属性和 Firebase Cloud Storage 上的文件存储
- python - 我想替换 sublimetext3 中的字母