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

React Native无法展示Fetch获取的NYTimes API数据,求代码修复

React Native NYTimes API数据渲染问题修复方案

核心问题定位

你的代码存在以下问题导致数据无法正常渲染:

  • API返回的完整JSON为对象类型,你直接将其赋值给数组类型的data状态,而FlatList仅支持数组作为数据源。本次请求的NYTimes接口中,实际书籍列表存放在json.results.books字段下
  • keyExtractor中读取的id字段在返回的书籍数据中不存在,无有效唯一标识会导致列表渲染异常
  • renderItem中读取的item.json为不存在的字段,无法展示有效内容
  • 搜索框searchquery无初始值,会触发React受控组件异常警告
  • 最外层View未设置flex:1,会导致FlatList无法正常占满容器展示内容

修复后完整代码

import React, { useEffect, useState } from 'react';
import { Text, View, FlatList, StyleSheet } from 'react-native';
import { Searchbar } from 'react-native-paper';

export default function Home() {
  const [searchquery, setSearchquery] = React.useState('');
  const [data, setData] = useState([]);

  const getBooks = async () => {
    try {
      const response = await fetch(
        `https://api.nytimes.com/svc/books/v3/lists/current/hardcover-fiction.json?api-key=9OTXA7aqliGSkwHKCACiw0SLkmfzMB6g`
      );
      const json = await response.json();
      // 仅提取书籍列表赋值给data,增加异常兜底
      setData(json.results?.books || []);
    } catch (error) {
      console.error(error);
    }
  };

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

  return (
    <View style={{flex: 1}}>
      <Searchbar
        placeholder="Search Books"
        onChangeText={(query) => setSearchquery(query)}
        value={searchquery}
        style={{ marginTop: 30, marginHorizontal: 10 }}
      />
      <FlatList
        data={data}
        // 使用书籍自带的ISBN作为唯一标识,增加索引兜底
        keyExtractor={(item, index) => item.primary_isbn13 || String(index)}
        renderItem={({ item }) => (
          <View style={styles.customCard}>
            <Text style={styles.bookTitle}>书名:{item.title}</Text>
            <Text style={styles.bookAuthor}>作者:{item.author}</Text>
            <Text style={styles.bookDesc}>简介:{item.description}</Text>
          </View>
        )}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  customCard: {
    padding: 15,
    marginTop: 15,
    marginHorizontal: 10,
    backgroundColor: 'lightgray',
    borderRadius: 8
  },
  bookTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 5
  },
  bookAuthor: {
    fontSize: 14,
    marginBottom: 8
  },
  bookDesc: {
    fontSize: 13,
    color: '#333'
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:15:02