axios请求+映射函数内部的react hooks导致无限循环

我正在尝试按项目显示任务数。用

调用axios请求
getTasksByProject(_id);

会导致一个循环,在该循环中经常设置“ nbrOfTasks”。我该如何预防?

//Schema
const taskSchema = new mongoose.Schema({
  title: String,project: { type: ObjectId,ref: 'Project' },})

const projectSchema = new mongoose.Schema ({
  name: String
})

代码:

const List = ({ match }) => {
  const [projects,setProject] = useState([]);
  const [nbrOfTasks,setNbrOfTasks] = useState();

  const getTasksByProject = ( _id) => {
    axios.get(`/api/tasks/tasksByProject/${_id}`)
    .then(response => {
      setNbrOfTasks(response.data.length);
    })
  }

  const loadProjects = () => {
    axios.get('/api/projects/').then(response => {
      setProject(response.data)
    })
  }

  useEffect(() => {
    loadProjects();
  },[])

  return (
    <>
      <Table singleLine columns={4} striped>
        <Table.Header>
          <Table.Row>
            <Table.HeaderCell>Name</Table.HeaderCell>
            <Table.HeaderCell>#Tasks</Table.HeaderCell>
          </Table.Row>
        </Table.Header>

        <Table.Body>
          {projects.map((project) => {
            const { _id,name,status,description } = project;

            getTasksByProject(_id);

            return (
              <Table.Row key={_id}>
                <Table.Cell>{`${name}`}</Table.Cell>
                <Table.Cell>{nbrOfTasks}</Table.Cell>
              </Table.Row>
            )
          })}
        </Table.Body>
      </Table>
    </>
  )
}

export default List;
jakela 回答:axios请求+映射函数内部的react hooks导致无限循环

猕猴桃,您不能在渲染函数中设置状态。(您已调用getTasksByProject(_id);在渲染函数中调用了状态改变状态并再次调用了渲染函数,依此类推)。这会导致无限循环。

您可以

const loadProjects = () => {
                axios.get('/api/projects/').then(response => {
                  response.data.map((project) => {
                        const { _id,name,status,description } = project;
                         axios.get(`/api/tasks/tasksByProject/${_id}`)
                .then(response => {


                })
      //here prepare new array with ({project_id,project_name,task length}) and use this array in render function instead

                })
              }

一个更好的解决方案是创建一个新端点,该端点将返回带有({project_id,project_name,task length})的数组

本文链接:https://www.f2er.com/3131901.html

大家都在问