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

React子组件未及时接收API传递数据问题求助

问题修复:React组件无法及时获取API数据导致渲染失败

问题根源

  1. 请求状态判断逻辑错误:finally会在请求完成(无论成功/失败)时触发,若请求失败data仍为null,此时status=true会直接尝试访问data[0],抛出Cannot read properties of null错误。
  2. 异步状态更新时机冲突:React的setState是异步操作,setData(result)后立刻执行setStatus(true),可能data还未完成更新就触发组件渲染,导致data[0]未定义。

修复后的代码

App.js

import React from 'react';
import Boxx from './Boxx';

function App(){
  const [data, setData] = React.useState(null);
  const [error, setError] = React.useState(null);

  React.useEffect(()=>{
    fetch('https://the-trivia-api.com/api/questions?categories=science,society_and_culture&limit=5')
      .then(res => {
        if (!res.ok) throw new Error('请求失败');
        return res.json();
      })
      .then(result => setData(result))
      .catch(err => setError(err.message));
  },[])

  if (error) return <div>加载失败:{error}</div>;
  if (!data || data.length === 0) return <div>加载中...</div>;

  return(
    <div className='App--'>
      <Boxx question={data[0].question} answers={data[0].answers} />
    </div>
  )
}

export default App;

Boxx.js

import React from "react";
import './index.css'

export default function Boxx (props) {
  const answers = props.answers || [];
  
  return(
    <div className="questionBody--">
      <p className='qB--question'>{props.question || '暂无问题'}</p>
      <div className="answers--">
        <p className="qB--answer" id='0'>{answers[1] || ''}</p>
        <p className="qB--answer" id='1'>{answers[0] || ''}</p>
        <p className="qB--answer" id='2'>{answers[2] || ''}</p>
      </div>
    </div>
  )
}

关键优化点

  • 移除冗余状态:直接通过data的存在性和数组长度判断渲染时机,贴合React状态管理逻辑。
  • 增加错误处理:捕获请求失败场景,给出友好提示,避免页面崩溃。
  • 组件防御性渲染:在Boxx中添加默认值兜底,防止props未传入时的报错。

内容的提问来源于stack exchange,提问作者housam-h

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:21:34