You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在React Navigation类组件中使用navigation.navigate遇错求助

解决React Navigation类组件中导航跳转的报错问题

核心错误定位

你代码里的导航调用存在拼写错误:navigation.navigation("Home") 应该改为 navigation.navigate("Home"),这是导致报错的直接原因。

完整修正后的代码

import { firebase } from "@react-native-firebase/auth";
import { useNavigation } from "@react-navigation/native";
import {
  Box,
  Button,
  Divider,
  HStack,
  Heading,
  ScrollView,
  Spinner,
  Text,
} from "native-base";
import React from "react";

function getIsQuestCompleted(querySnapshot: any) {
  return querySnapshot.get("key");
}

class TaskTrackingComp extends React.Component {
  state = {
    savedKey: "",
    ttrkerData: [],
    loading: true,
  };

  getTarkovTrackerData = async () => {
    try {
      const res = await fetch("https://tarkovtracker.io/api/v2/progress", {
        method: "GET",
        headers: {
          Authorization: `Bearer ${this.state.savedKey}`,
        },
      });
      const data = await res.json();
      this.setState({
        ttrkerData: data,
        loading: false,
      });
    } catch (err) {
      console.error("获取Tracker数据失败:", err);
      this.setState({ loading: false });
    }
  };

  componentDidMount() {
    // 移到组件挂载时获取用户,避免初始化时currentUser为空
    const user = firebase.auth().currentUser;
    if (!user) {
      console.error("用户未登录");
      this.setState({ loading: false });
      return;
    }

    firebase
      .firestore()
      .collection("UserApiKeys")
      .doc(user.uid)
      .get()
      .then((querySnapshot) => getIsQuestCompleted(querySnapshot))
      .then((savedKey) => {
        console.log("Saved Key", savedKey);
        this.setState({ savedKey });
        this.getTarkovTrackerData();
      })
      .catch((err) => {
        console.error("获取API Key失败:", err);
        this.setState({ loading: false });
      });
  }

  render() {
    const { navigation } = this.props;
    console.log("savedKey state:", this.state.savedKey);
    console.log("Tarkov Tracker Data state:", this.state.ttrkerData);
    console.log("Loading?", this.state.loading);

    return (
      <ScrollView>
        <Box justifyContent={"center"} alignItems={"center"}>
          <Heading fontWeight={"extrabold"}>Tarkov Tracker Stats</Heading>
        </Box>
        <Divider />
        {this.state.loading ? (
          <HStack space={2} justifyContent={"center"} alignItems={"center"}>
            <Box>
              <Text>Getting Stats</Text>
            </Box>
            <Box>
              <Spinner color="warning.500" />
            </Box>
          </HStack>
        ) : (
          <Box justifyContent={"center"} alignItems={"center"}>
            <Button onPress={() => navigation.navigate("Home")}>返回首页</Button>
          </Box>
        )}
      </ScrollView>
    );
  }
}

export default function TaskTracking(props: any) {
  const navigation = useNavigation();
  return <TaskTrackingComp {...props} navigation={navigation} />;
}

额外优化说明

  • 修正了导航方法名的拼写错误,这是触发报错的核心问题。
  • 给所有异步操作添加了错误捕获逻辑,避免未处理的异常导致组件崩溃。
  • 将用户信息的获取移到componentDidMount中,解决组件初始化阶段currentUser可能未完成初始化的问题。
  • 调整了savedKey的初始值为字符串(API Key通常为字符串类型),避免请求时出现格式错误。
  • 给按钮添加了文本内容,提升交互识别性。

内容的提问来源于stack exchange,提问作者MatDoak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 12:01:53