[英]React Hook "useCustomHook" is called conditionally. React Hooks must be called in the exact same order in every component render
I got error when i want to set if in customHook Code当我想在 customHook 代码中设置 if 时出现错误
if (dataValid) {
const contactForm = useDataForm(onSubmit, modelToForm(dataValid));
}
After this i got error ->在此之后我得到错误->
React Hook "useDataForm" is called conditionally. React Hooks must be called in the exact same order in every component render
Problem is if statment when call this work good ( without if ) ->问题是如果调用这项工作时的陈述很好(没有 if )->
const contactForm = useDataForm(onSubmit, modelToForm(dataValid));
I wan't to load useDataForm ( custom hook ) if dataValid not valid and filled.如果dataValid无效且已填充,我不想加载 useDataForm (自定义挂钩)。
We can't call Hooks inside of conditionals, loops, or nested functions in order to ensure that Hooks are called in the same order each time a component renders.我们不能在条件、循环或嵌套函数中调用 Hooks,以确保每次渲染组件时都以相同的顺序调用 Hooks。 The order is important for how React associates Hook calls with components.
该顺序对于 React 如何将 Hook 调用与组件关联起来很重要。
Resource: https://www.benmvp.com/blog/conditional-react-hooks/#:~:text=We%20can%27t%20call%20Hooks,associates%20Hook%20calls%20with%20components .资源: https://www.benmvp.com/blog/conditional-react-hooks/#:~:text=We%20can%27t%20call%20Hooks,associates%20Hook%20calls%20with%20components 。
You can check this resource maybe it can be helpful您可以查看此资源,也许它会有所帮助
As per React documentation, you cannot call hooks conditionally .根据 React 文档, 您不能有条件地调用钩子。
Here is explained in depth why.这里深入解释为什么。
When the need to call a hook conditionally arises, you could opt for two soutions:当需要有条件地调用钩子时,您可以选择两种解决方案:
useDataForm
and then you use contactForm
only if dataValid
is true
useDataForm
,然后仅当dataValid
为true
时才使用contactForm
const contactForm = useDataForm(onSubmit, modelToForm(dataValid));
if (dataValid) {
// do what you need to do with dataValid
}
// or
return <Child data={dataValid ? contactForm : otherData} />
dataValid
is truedataValid
为 true 时才呈现所述组件const contactForm = useDataForm(onSubmit, dataValid ? modelToForm(dataValid) : fallbackArg);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.