You need to enable JavaScript to run this app. React使用Axios拉取mock API数据渲染时报Cannot read property 'quote'错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

React使用Axios拉取mock API数据渲染时报Cannot read property 'quote'错误如何解决

报错原因分析
  • 初始渲染时访问空数组元素:你给quotes状态的初始值是空数组[],组件首次渲染时接口请求还没返回,此时quotes[quoteIndex]就是undefined,访问undefined的quote属性就会抛出该错误。
  • 接口返回数据赋值错误:从你给出的JSON示例来看,接口返回的完整结构外层有quotes字段包裹数组,如果你直接把response.data赋值给quotes状态,相当于把外层对象当成数组存储,后续按索引取值自然取不到对应对象。
修复方案

1. 修正接口数据赋值逻辑

调整getData里的状态赋值代码,取response.data里的quotes数组赋值:

const getData = async() =>{
  try{
    const response = await Axios.get("/quotes");
    if(response && response.data?.quotes){
      setQuotes(response.data.quotes);
      console.log(response.data.quotes);
    }
  }catch(error){
    console.log(error);
  }
}

2. 渲染时增加安全访问判断

可以用可选链运算符规避空值访问报错,也可以加条件渲染在数据未加载完成时显示占位内容:

// 可选链写法,兼容空值场景
<div className="styleQuote">
  <h3 className="styleText" >{quotes[quoteIndex]?.quote || '加载中...'}</h3>
</div>

// 或者条件渲染写法
{quotes.length > 0 ? (
  <div className="styleQuote">
    <h3 className="styleText" >{quotes[quoteIndex].quote}</h3>
  </div>
) : <p>名言加载中...</p>}

3. 可选:新增loading状态优化体验

可以单独加一个loading状态控制加载逻辑,避免数据加载阶段的异常渲染:

const [quotes, setQuotes] = useState([]);
const [quoteIndex, setQuoteIndex] = useState(0);
const [loading, setLoading] = useState(true);

const getData = async() =>{
  try{
    setLoading(true);
    const response = await Axios.get("/quotes");
    if(response && response.data?.quotes){
      setQuotes(response.data.quotes);
    }
  }catch(error){
    console.log(error);
  }finally{
    setLoading(false);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 06:54:04