gpt4 book ai didi

reactjs - 在普通函数中使用 react navigation.navigate -(不允许 Hook ,即 useNavigation)?

转载 作者:行者123 更新时间:2023-12-05 03:55:07 27 4
gpt4 key购买 nike

我试图在另一个模块中放置一个导航到屏幕的函数并将其导出,但是 navigation 不起作用。我尝试使用 UseNavigation() 但出现错误,即:Unhandled promise rejection: Invariant Violation: Hooks can only be called inside 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;

在你的主屏幕/ View 中

    const HomeScreen = ({navigation}) => {
useEffect(() => {
navigationService.navigation = navigation;
}, [navigation]);
....

现在到处都可以做到这一点

import navigationService from '../services/navigation';

navigationService.navigation.navigate('Screen');

关于reactjs - 在普通函数中使用 react navigation.navigate -(不允许 Hook ,即 useNavigation)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60463343/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com