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

使用Async/Await请求数据导致React组件持续重渲染问题

解决React组件调用Async/Await接口导致的无限重渲染问题

问题原因

你直接在组件函数体内调用getStudent(),组件每次渲染时都会执行这个函数,而setStudent(data)会更新状态触发组件重新渲染,形成无限循环,导致持续重渲染。

解决方案

用useEffect钩子包裹数据请求,通过依赖数组控制执行时机:

import { useState, useEffect } from "react";
import Axios from "axios";

const DashBoard = () => {
  const [student, setStudent] = useState<{ [key: string]: string }[]>([]);
  const studentId = JSON.parse(localStorage.getItem("studentId") as string);
  const examResult: { [key: string]: string }[] = JSON.parse(
    localStorage.getItem("englishAnswers") as string
  );

  const getStudent = async () => {
    const { data } = await Axios.get(
      `http://localhost:3500/students/${studentId}`
    );
    setStudent(data);
  };

  // 仅在组件挂载或studentId变化时执行请求
  useEffect(() => {
    getStudent();
  }, [studentId]);
};
  • 如果只需要组件首次挂载时请求一次,把依赖数组改成空数组[]即可。
  • 依赖数组里的studentId是为了保证当用户ID变化时,能重新请求对应的数据。

可选优化:添加加载与错误处理

为了提升用户体验,建议加上加载状态和错误捕获:

import { useState, useEffect } from "react";
import Axios from "axios";

const DashBoard = () => {
  const [student, setStudent] = useState<{ [key: string]: string }[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const studentId = JSON.parse(localStorage.getItem("studentId") as string);
  const examResult: { [key: string]: string }[] = JSON.parse(
    localStorage.getItem("englishAnswers") as string
  );

  const getStudent = async () => {
    try {
      setLoading(true);
      const { data } = await Axios.get(
        `http://localhost:3500/students/${studentId}`
      );
      setStudent(data);
      setError(null);
    } catch (err) {
      setError("获取学生数据失败");
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    getStudent();
  }, [studentId]);

  if (loading) return <div>加载中...</div>;
  if (error) return <div>{error}</div>;

  // 渲染学生数据
  return <div>{/* 你的渲染逻辑 */}</div>;
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:10:47