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

React Native使用Axios调用游戏新闻API无数据返回问题排查

GTA新闻API调用失败排查方案

问题背景

调用游戏新闻API获取GTA相关新闻时无法拿到数据,怀疑API返回格式为字符串导致问题。以下是API返回示例和组件代码:

API返回数据示例

{
  "title": "GTA 6 release date rumours, news, and speculation",
  "date": "Fri, 03 Feb 2023 17:06:57 +0000",
  "description": "Want to know more about the GTA 6 release date? Given how many years it takes to create open worlds of the same calibre as GTA V, it’s no surprise that Rockstar Games has already spent years developing GTA 6. Like most developers, Rockstar prefers to keep its secrets close to its chest until they’re close to the end of development, so we may not see any official GTA 6 gameplay for some time. Early gameplay footage of GTA 6 recently surfaced online, along with lines of source code from the game itself. Rockstar has issued a statement on Twitter which confirms that an unauthorised third party managed to access and download information from their systems, including development footage for the open-world game. However, its statement notes that the developers don’t believe this leak should impact the development of their long-term projects or disrupt their live service games.",
  "image": "https://www.pcgamesn.com/wp-content/sites/pcgamesn/2022/02/gta-6-release-date-2022.jpg",
  "link": "https://www.pcgamesn.com/grand-theft-auto-vi/gta-6-release-date-setting-map-characters-gameplay-trailers"
}

原Games组件代码

import { StyleSheet, SafeAreaView, FlatList } from "react-native";
import axios from "axios";
import { useState, useEffect } from "react";
import Article from "../components/Article";

export default function Games() {
  let [articles, setArticles] = useState([]);

  const getArticle = () => {
    axios
      .get({
        method: "GET",
        url: "https://videogames-news2.p.rapidapi.com/videogames_news/search_news",
        params: { query: "GTA" },
        headers: {
          "X-RapidAPI-Key":
            "8114fa0745msh7596481771a0acbp1eb7e4jsnaae758420c49",
          "X-RapidAPI-Host": "videogames-news2.p.rapidapi.com",
        },
      })
      .then(function (response) {
        setArticles(response.data);
      })
      .catch(function (error) {
        console.log("error", error);
      })
      .finally(function () {
        setLoading(true);
      });
  };
  useEffect(() => {
    getArticle();
  }, []);

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={articles}
        renderItem={({ item }) => (
          <Article
            image={item.image}
            title={item.title}
            description={item.description}
            sourceName={item.source.name}
          />
        )}
        keyExtractor={(item) => item.title}
      />
    </SafeAreaView>
  );
}

排查出的问题及修复方案

1. Axios GET请求写法错误

axios.get()的正确用法是第一个参数传URL,第二个参数传配置对象(包含headers、params等),直接传配置对象会导致请求发送失败。

修复后请求代码:

axios.get(
  "https://videogames-news2.p.rapidapi.com/videogames_news/search_news",
  {
    params: { query: "GTA" },
    headers: {
      "X-RapidAPI-Key": "8114fa0745msh7596481771a0acbp1eb7e4jsnaae758420c49",
      "X-RapidAPI-Host": "videogames-news2.p.rapidapi.com",
    },
  }
)

2. API返回数据结构与代码不匹配

  • API返回的是单个新闻对象,但代码直接将其赋值给数组类型的articles,FlatList无法渲染单个对象,需将其包装为数组。
  • Article组件中使用了item.source.name,但API返回字段里没有source属性,会导致报错,需移除该属性或确认API实际返回字段。

修复数据处理逻辑:

.then(function (response) {
  // 将单个对象转为数组
  setArticles([response.data]);
})

同时修改FlatList的renderItem:

<Article
  image={item.image}
  title={item.title}
  description={item.description}
  // 移除不存在的source.name属性
/>

3. 未定义loading状态

代码中finally块调用了setLoading(true),但未声明loading状态变量,会导致报错。需添加状态声明或移除无用的setLoading调用。

添加loading状态(若需要):

let [articles, setArticles] = useState([]);
let [loading, setLoading] = useState(false); // 添加状态声明

4. 验证API返回是否为字符串(针对你的怀疑)

如果API确实返回JSON字符串而非解析后的对象,可在响应中手动解析:

.then(function (response) {
  const data = typeof response.data === 'string' ? JSON.parse(response.data) : response.data;
  setArticles([data]);
})

完整修复后的组件代码

import { StyleSheet, SafeAreaView, FlatList, Text } from "react-native";
import axios from "axios";
import { useState, useEffect } from "react";
import Article from "../components/Article";

export default function Games() {
  const [articles, setArticles] = useState([]);
  const [loading, setLoading] = useState(false);

  const getArticle = () => {
    setLoading(true);
    axios.get(
      "https://videogames-news2.p.rapidapi.com/videogames_news/search_news",
      {
        params: { query: "GTA" },
        headers: {
          "X-RapidAPI-Key": "8114fa0745msh7596481771a0acbp1eb7e4jsnaae758420c49",
          "X-RapidAPI-Host": "videogames-news2.p.rapidapi.com",
        },
      }
    )
    .then(function (response) {
      const data = typeof response.data === 'string' ? JSON.parse(response.data) : response.data;
      setArticles([data]);
    })
    .catch(function (error) {
      console.error("请求错误:", error);
    })
    .finally(function () {
      setLoading(false);
    });
  };

  useEffect(() => {
    getArticle();
  }, []);

  return (
    <SafeAreaView style={styles.container}>
      {loading ? (
        <Text>加载中...</Text>
      ) : (
        <FlatList
          data={articles}
          renderItem={({ item }) => (
            <Article
              image={item.image}
              title={item.title}
              description={item.description}
            />
          )}
          keyExtractor={(item) => item.title}
        />
      )}
    </SafeAreaView>
  );
}

内容的提问来源于stack exchange,提问作者Antonio Kovačić

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 16:05:53