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

React Native中如何从API取数据并在FlatList渲染

问题分析与解决方案

你的代码存在两个核心问题:

  • 未将API返回的数据存入状态变量,导致FlatList没有可渲染的数据源
  • 对RapidAPI足球赛事接口的返回结构理解有误,错误尝试访问data.fixture,实际赛事数据存放在response.data.response数组中

修正后的代码

import React, { useEffect, useState } from "react";
import { FlatList, Text, View } from "react-native";
import axios from "axios";

function NotificationScreen() {
  const [isLoading, setLoading] = useState(true);
  // 初始状态设为空数组,匹配返回的数据结构
  const [fixtures, setFixtures] = useState([]);

  const options = {
    method: "GET",
    url: "https://api-football-v1.p.rapidapi.com/v3/fixtures",
    params: {
      league: "39",
      season: "2022",
      from: "2023-02-04",
      to: "2023-02-05",
    },
    headers: {
      "X-RapidAPI-Key": "mykey",
      "X-RapidAPI-Host": "api-football-v1.p.rapidapi.com",
    },
  };

  useEffect(() => {
    axios
      .request(options)
      .then(function (response) {
        // 提取接口返回的赛事数据数组并更新状态
        setFixtures(response.data.response);
      })
      .catch(function (error) {
        console.error(error);
      })
      .finally(() => setLoading(false));
  }, []);

  return (
    <View style={{ flex: 1, padding: 24, backgroundColor: "purple" }}>
      {isLoading ? (
        <Text>Loading...</Text>
      ) : (
        <View
          style={{
            flex: 1,
            flexDirection: "column",
            justifyContent: "space-between",
          }}
        >
          <Text style={{ fontSize: 20, color: "white", textAlign: "center" }}>
            Fetch content using Axios
          </Text>
          <Text
            style={{
              fontSize: 14,
              color: "white",
              textAlign: "center",
              paddingBottom: 10,
            }}
          >
            赛事列表:
          </Text>
          <FlatList
            // 使用修正后的数据源
            data={fixtures}
            // 赛事ID嵌套在fixture对象中,需正确提取并转为字符串
            keyExtractor={(item) => item.fixture.id.toString()}
            renderItem={({ item }) => (
              <Text style={{ color: "white", padding: 8 }}>
                赛事ID: {item.fixture.id}
              </Text>
            )}
          />
        </View>
      )}
    </View>
  );
}

export default NotificationScreen;

关键修改说明

  1. 状态变量优化:将data改为fixtures,更贴合数据含义,初始值设为空数组
  2. 数据存储修正:在axios的then回调中,通过setFixtures(response.data.response)把API返回的赛事数组存入状态
  3. FlatList配置修正:数据源改为fixtures,同时调整keyExtractor正确提取嵌套的赛事ID,并转为字符串类型(React Native要求key为字符串)
  4. 无效代码移除:删除了原代码中{data.title}的渲染,因为该接口返回数据中不存在title字段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 04:05:19