Rendered more hooks than during the previous render. react

huangapple go评论68阅读模式
英文:

Rendered more hooks than during the previous render. react

问题

当我尝试使用这个函数时,我遇到了错误:在上一次渲染时渲染了更多的钩子。

export const employeesExtraHours = (
  employees: any[],
  holidays: any[],
  rules: any[],
  types: any[],
  startDate: string,
  endDate: string
): any[] => {
  return employees.map((employee) => {
    const request = useFetchTimeOffRequests(
      employee.bambooHREmployeeId,
      startDate,
      endDate
    );

    const extraHoursData = ExtraHoursData(
      employee.bambooHREmployeeId,
      employee.displayName,
      startDate,
      endDate,
      holidays,
      rules,
      types,
      request
    );

    // You can store the extraHoursData in the employee object
    return {
      ...employee,
      extraHoursData,
    };
  });
};

我必须为每个员工使用这个钩子。

新的员工数组列表。

英文:

when i try using this function i got error :Rendered more hooks than during the previous render.

export const employeesExtraHours = (
  employees: any[],
  holidays: any[],
  rules: any[],
  types: any[],
  startDate: string,
  endDate: string
): any[] => {
  return employees.map((employee) => {
    const request = useFetchTimeOffRequests(
      employee.bambooHREmployeeId,
      startDate,
      endDate
    );

    const extraHoursData = ExtraHoursData(
      employee.bambooHREmployeeId,
      employee.displayName,
      startDate,
      endDate,
      holidays,
      rules,
      types,
      request
    );

    // You can store the extraHoursData in the employee object
    return {
      ...employee,
      extraHoursData,
    };
  });
};

i have to use the hook for every employee

new array list of employee

答案1

得分: 1

这里有两个错误:

  • 在普通函数中使用钩子。employeesExtraHours只是一个函数,而你在其中调用了useFetchTimeOffRequests。钩子应该只在组件和自定义钩子中使用。
  • 在循环中使用钩子。钩子调用的次数不应在渲染之间改变。如果无法保证这一点,就不应该在循环内调用钩子。

你可以将钩子调用移动到一个用于为每个员工呈现的组件中。或者,如果useFetchTimeOffRequests内部没有使用任何钩子,你可以将其转换为普通函数,然后可以在那里调用它。

这一切都在React文档中有解释。

英文:

Here you have 2 mistakes

  • Using hook inside regular function. employeesExtraHours is just a function and you are calling useFetchTimeOffRequests inside it. Hooks should be used only inside components and custom hooks
  • Using hook inside a loop. The number of hook calls should not change between renders. If you can't guarantee that, you should not call hooks inside loops.

What you can do is to move the hook call inside a component that you use to render for each employee. Or if useFetchTimeOffRequests is not using any hooks inside it, you can transform it into regular function, then you will be able to call it there

It is all explained in the React docs

huangapple
  • 本文由 发表于 2023年7月6日 17:25:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76627368.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定