尝试遵循docs中的示例,在更新函数中的状态时遇到无限循环。代码如下:
Home.jsx:
...
import { studentDefaults } from "./student";
import { getStudent } from "./api";
function useStudent() {
const [student, setStudent] = useState(studentDefaults);
function handleStudentChange(student) {
setStudent(student);
}
// Fetch the student after mount
useEffect(() => {
getStudent(handleStudentChange);
});
return student;
}
function StudentForm(props) {
// Use the student here
const student = useStudent();
return ( <MyComponent student={student} /> )
}
api.js:
import request from "request-promise";
import { auth } from "./firebase/firebase";
const url =
"http://localhost:5000/projectID/region/api";
export const getStudent = async handleStudentChange => {
try {
const token = await auth.currentUser.getIdToken(false);
const student = await request(url + `?token=${token}`);
handleStudentChange(student);
} catch (e) {
console.error(e);
}
};
所有这些都正确地获取和设置,但是它进入了递归循环,我不知道为什么。
答案 0 :(得分:2)
每次运行useEffect
时,都会运行useStudent
中的useStudent
。由于您正在更新赋予它的功能中的状态,因此它将无限期地循环。
通过将空数组作为useEffect
的第二个参数,您可以使它成为空,以便在初始渲染后仅运行一次。
function useStudent() {
const [student, setStudent] = useState(studentDefaults);
function handleStudentChange(student) {
setStudent(student);
}
// Fetch the student after mount
useEffect(() => {
getStudent(handleStudentChange);
}, []);
return student;
}