英文:
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 callinguseFetchTimeOffRequests
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论