尝试遵循文档中的示例,我在更新函数中的状态时遇到了无限循环。代码如下:
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);
}
};
这一切都正确地获取和设置,但它进入了一个递归循环,我不知道为什么。