[英]Why I am getting this error “React has detected a change in the order of Hooks called by SidebarDesktop”?
I declare a const in my SideBarDesktop component name isSidebarSticky
which use a custom hook( useStickyElement
) that has 2 arguments:我在我的 SideBarDesktop 组件名称isSidebarSticky
中声明了一个 const,它使用具有 2 个 arguments 的自定义钩子( useStickyElement
):
const isSidebarSticky = styleStore.contentHeight
? useStickyElement(sideBarDomRef, styleStore.headerHeight + styleStore.contentHeight)
: 0;
The problem is that I'm getting this error: "React has detected a change in the order of Hooks called by SidebarDesktop. This will lead to bugs and errors if not fixed."问题是我收到了这个错误:“React 检测到 SidebarDesktop 调用 Hook 的顺序发生了变化。如果不修复,这将导致错误和错误。” and I don't know why.我不知道为什么。
PS If I'm not making that verification and I just write: PS如果我没有进行验证,我只是写:
const isSidebarSticky = useStickyElement(sideBarDomRef, styleStore.headerHeight + styleStore.contentHeight);
I'm not getting the error anymore.我不再收到错误消息了。
The thing is that if I use the second example styleStore.contentHeight is not updated on time(it's 0) and I have to make that verification, otherwise the result will be useStickyElement(sideBarDomRef, styleStore.headerHeight + 0)
.问题是,如果我使用第二个示例 styleStore.contentHeight 没有按时更新(它是 0),我必须进行验证,否则结果将是useStickyElement(sideBarDomRef, styleStore.headerHeight + 0)
。 Even though styleStore.contentHeight
will be greater then 0 eventually the useStickyElement
will not be called anymore.即使styleStore.contentHeight
会大于 0,最终useStickyElement
也不会被调用。
React hooks can not be conditional. React 钩子不能是有条件的。 See https://reactjs.org/docs/hooks-rules.html见https://reactjs.org/docs/hooks-rules.html
You can not enter terms in the call to hooks您不能在对钩子的调用中输入术语
If there are cases where the hooks are not called React he will not be able to compare the runs and he fails如果在某些情况下钩子不被称为 React,他将无法比较运行并且他失败了
Conditions can be inserted inside the hooks条件可以插入到钩子里面
see here explanation in docs请参阅文档中的此处说明
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.