【发布时间】:2023-01-30 23:41:39
【问题描述】:
我在尝试使用 axios 从后端获取数据时遇到问题。该函数返回一个 Promise,每当我调用该函数时,我的组件都会不停地渲染。这是代码。
import { useState } 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);
};
getStudent(); //this line here keeps triggering re-render non stop;
【问题讨论】:
-
你不应该在渲染阶段发起 HTTP 网络请求(除非你在服务器组件中这样做)。了解更多关于API requests in reactJs here
标签: reactjs typescript axios