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

React应用中Fetch API返回结果无法显示,寻求技术解决方案

问题原因与解决方法

核心问题是你直接在JSX中渲染JavaScript对象quote,React无法直接解析并渲染对象类型的数据,所以页面显示空白。而Node.js环境中能正常运行是因为Node仅在控制台打印对象,不需要将其转换为DOM元素。

解决步骤

  1. 确认请求状态:打开浏览器控制台的Network标签,会发现请求其实是成功的,问题出在渲染逻辑上。
  2. 修改渲染方式:访问quote对象的具体属性(zenquotes返回的对象包含q(名言内容)、a(作者)等属性),而非直接渲染整个对象。
  3. 增加状态管理:添加加载、错误状态,提升用户体验同时便于排查问题。

修改后的完整代码

import { useEffect, useState } from 'react'

export default function Home() {
  const [quote, setQuote] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  
  useEffect(() => {
    fetch('https://zenquotes.io/api/random')
      .then(res => {
        // 检查响应状态是否正常
        if (!res.ok) {
          throw new Error(`请求失败:${res.status}`)
        }
        return res.json()
      })
      .then(data => {
        setQuote(data[0])
        setLoading(false)
      })
      .catch(err => {
        setError(err.message)
        setLoading(false)
        console.error(err)
      })
  }, [])
  
  // 加载状态
  if (loading) return <main>加载中...</main>
  // 错误状态
  if (error) return <main>出错了:{error}</main>
  
  return (
    <main style={{ padding: '2rem', maxWidth: '600px', margin: '0 auto' }}>
      <blockquote style={{ borderLeft: '4px solid #ccc', paddingLeft: '1rem', fontStyle: 'italic' }}>
        <p>{quote.q}</p>
        <footer style={{ marginTop: '1rem', textAlign: 'right', fontWeight: 'bold' }}>— {quote.a}</footer>
      </blockquote>
    </main>
  )
}

补充说明

  • 你之前尝试的Axios和proxy配置无效,因为根本问题不是请求失败或跨域(跨域会在控制台抛出明确的CORS错误),而是渲染逻辑错误。
  • 增加响应状态检查,可以捕获接口返回的非成功状态(如404、500),避免隐性错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 00:38:27