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

ReactJS:API返回数据后动态更新HTML问题【已解决】

问题解决:API返回数据后HTML未更新的修复

核心问题

你的代码中存在两个关键问题:

  • 后端返回的数据结构是包含Match数组的对象,但你直接把整个响应对象赋值给了matchInfo,导致matchInfo.length始终为0(因为对象没有length属性)
  • 错误使用了函数式更新语法,这里不需要依赖之前的state值,直接赋值即可

修复步骤

  • 修正state赋值逻辑:将setMatchInfo的参数改为response.data.Match,确保matchInfo存储的是实际的比赛数据数组
  • 调整渲染判断条件:将matchInfo.length > 0改为matchInfo?.length > 0,增加可选链操作符避免空值报错
  • 优化setState调用:去掉不必要的函数式更新写法,直接传递新值

修复后的完整代码

export default function NRL() {
  const [week, setWeek] = useState();
  const [season, setSeason] = useState();
  const [matchInfo, setMatchInfo] = useState([]);

  function handleButtonClick() {
    console.log('getting data: Week: ' + week + ' Season: ' + season);
    axios.get('/nrl/', {
      params: { week, season }
    }).then(response => {
      console.log(response);
      // 直接赋值响应中的Match数组
      setMatchInfo(response.data.Match);
    });
  }

  return (
    <>
      <div className="page-title">
        <h1>NRL</h1>
      </div>
      
      <div className="input-fields">
        <input 
          className="userIn"
          placeholder="Enter Round"
          name="weekIn" 
          value={week}
          onChange={(e) => setWeek(e.target.value)}
        />
        
        <input 
          className="userIn"
          placeholder="Enter Season"
          name="seasonIn" 
          value={season}
          onChange={(e) => setSeason(e.target.value)}
        />

        <button onClick={handleButtonClick}>Get Data</button>  
      </div>

      {/* 使用可选链操作符,确保数组存在时再渲染 */}
      {matchInfo?.length > 0 && (
        <div className="display-match-info">
          {matchInfo.map((item, i) => (
            // 为每个列表项添加唯一key,符合React规范
            <p key={i}>{item.date}</p>
          ))}
        </div>
      )}
    </>
  );
}

额外优化建议

  • 为map生成的列表项添加唯一key属性(这里用索引i临时替代,实际项目中建议使用数据中的唯一ID)
  • 可以添加加载状态,在API请求过程中显示加载提示,提升用户体验
  • 为输入框添加类型限制(比如数字类型),避免无效参数请求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:27:31