试图按照文档中的示例进行操作,在更新函数中的状态时遇到了无休止的循环。代码如下:
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);
}
};
这一切都是正确的获取和设置,但它进入了一个递归循环,我不知道为什么。
useStudent
中的useEffect
将在每次运行useStudent
时运行。由于您正在更新给定给它的函数中的状态,它将无限循环。
通过将空数组作为useEffect
的第二个参数,可以使其在初始渲染后只运行一次。
function useStudent() {
const [student, setStudent] = useState(studentDefaults);
function handleStudentChange(student) {
setStudent(student);
}
// Fetch the student after mount
useEffect(() => {
getStudent(handleStudentChange);
}, []);
return student;
}