本文介绍: hooks使用规则* 只能在函数最外层调用 Hook。不要在循环、条件判断或者子函数中调用。* 只能在 React 的函数组件中调用 Hook。**不要在其他 JavaScript 函数中调用**。(还有一个地方可以调用 Hook —— 就是自定义的 Hook 中)
React Hook之钩子调用规则(不在循环、条件判断或者嵌套函数中调用)
hooks使用规则
错误使用案例
代码:
报错:
React Hook “useCustomItemRender” is called in function “customItemRender: ItemRender” that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word “use”.
报错解释:
这个错误表明你在React函数组件中使用了名为useCustomItemRender的自定义钩子(Hook),而这个钩子的使用发生在一个内嵌函数customItemRender中。React的钩子(Hooks)只能在函数组件的主体或者其他钩子中调用,而不能在嵌套函数或者控制流逻辑中调用。这个规则被称为“钩子调用规则”。
解决方法:
确保useCustomItemRender只在组件的主体中调用一次。如果customItemRender是一个独立的函数,你应该将useCustomItemRender的调用移到customItemRender函数外部,确保它不会在customItemRender内部被调用。如果customItemRender是一个React组件,那么应该将useCustomItemRender的调用保持在该组件的主体中。
案例具体解决方法
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。