首页 > 解决方案 > 在普通函数中使用 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"
        }
      });
    }
  }

};

谢谢

标签: reactjsreact-nativereact-navigationreact-native-navigation

解决方案


是的,使用单例服务保存对导航的引用,在您的应用程序的根目录中使用 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');

推荐阅读