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

React中Fetch数据在控制台显示但无法在页面展示的问题

问题分析与修复方案

你的代码存在几个关键问题,导致电影数据无法在页面正常渲染:

  • 数据结构处理错误:API返回的响应是包含results数组的对象,你直接把整个响应对象存入data,没有提取里面的电影列表数组。
  • 遍历逻辑错误:用[data].map(...)把data包装成新数组,导致遍历的是整个响应对象(或列表数组作为单个元素),而非每一部电影。
  • 图片路径取值错误:API返回的primaryImage是包含url字段的对象,直接用item.primaryImage作为图片src取不到有效路径。
  • key属性写法错误:key= "{item.id}"的多余引号会让key值变成字符串"{item.id}",而非电影实际的id值。

修复后的完整代码

function App() {
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  const url = 'https://moviesdatabase.p.rapidapi.com/titles';

  const apiGet = async () => { 
    setIsLoading(true);
    try {
      const response = await fetch(url, { 
        method: 'GET', 
        headers: {
          'X-RapidAPI-Key': '你的API密钥',
          'X-RapidAPI-Host': 'moviesdatabase.p.rapidapi.com'
        }
      });
      const json = await response.json();
      // 提取核心的电影列表数组
      setData(json.results || []);
    } catch (error) {
      console.error('请求出错:', error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <>
      <h3>电影数据库</h3>
      <button onClick={apiGet} disabled={isLoading}>
        {isLoading ? '加载中...' : '获取电影数据'}
      </button>
      <br /><br />

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))', gap: '1rem' }}>
        {isLoading ? (
          <p>加载中...</p>
        ) : data.length === 0 ? (
          <p>暂无数据</p>
        ) : (
          data.map((item) => (
            <div key={item.id} style={{ textAlign: 'center' }}>
              {/* 用可选链避免无图片时抛出错误 */}
              <img 
                src={item.primaryImage?.url} 
                alt={item.titleText?.text || '无标题'}
                style={{ width: '100%', height: 'auto', borderRadius: '4px' }}
              />
              {/* 显示电影标题 */}
              <p style={{ margin: '0.5rem 0 0' }}>{item.titleText?.text}</p>
            </div>
          ))
        )}
      </div>
    </>
  )
}

额外优化说明

  1. 改用async/await写法,比链式then更易读和维护
  2. 添加加载状态isLoading,防止重复点击按钮,同时给用户明确反馈
  3. 增加错误捕获逻辑,避免请求失败时页面无响应
  4. 补充空状态提示,无数据时显示友好信息
  5. 用CSS Grid实现响应式布局,电影卡片自动适配屏幕宽度
  6. 给图片添加alt属性,提升页面可访问性
  7. 用可选链操作符?.处理部分电影无图片/标题的异常情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 23:38:20