1

尝试遵循文档中的示例,我在更新函数中的状态时遇到了无限循环。代码如下:

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);
  }
};

这一切都正确地获取和设置,但它进入了一个递归循环,我不知道为什么。

4

1 回答 1

2

每次运行时都会运行 内部useEffect。由于您正在更新赋予它的函数中的状态,因此它将无限循环。useStudentuseStudent

通过给useEffect你一个空数组作为第二个参数,让它在初始渲染后只运行一次。

function useStudent() {
  const [student, setStudent] = useState(studentDefaults);

  function handleStudentChange(student) {
    setStudent(student);
  }

  // Fetch the student after mount
  useEffect(() => {
    getStudent(handleStudentChange);
  }, []);

  return student;
}
于 2018-11-05T13:07:16.397 回答