[英]React Hook must be called in the exact same order BUT I got an exception
I've already understood "React Hook must be called in the exact same order."我已经理解了“必须以完全相同的顺序调用 React Hook”。
So I think in following case it might be an error所以我认为在以下情况下它可能是一个错误
export default function(onClick) {
if (typeof onClick !== "function") {
return;
}
const element = useRef();
useEffect(() => {
if (element.current) {
element.current.addEventListener("click", onClick);
element.current.style.cursor = "pointer";
}
return () => {
if (element.current) {
element.current.removeEventListener("click", onClick);
}
};
}, []);
return element;
}
But this code works.但是这段代码有效。 I don't know why.., And I have other one.
我不知道为什么..,我还有另一个。 this is driving me crazy.
这真让我抓狂。
Look at this case:看这个案例:
export default function onClick(onClick) {
if (typeof onClick !== "function") {
return;
}
const element = useRef();
useEffect(() => {
if (element.current) {
element.current.addEventListener("click", onClick);
element.current.style.cursor = "pointer";
}
return () => {
if (element.current) {
element.current.removeEventListener("click", onClick);
}
};
}, []);
return element;
}
I just named function and It give an error to me...我刚刚命名为 function 并且它给我一个错误...
Please let me know why upper case's hook is not an error?请让我知道为什么大写的钩子不是错误?
I got it!我知道了!
It is just ES-lint's bug这只是 ES-lint 的错误
cf) https://github.com/facebook/react/issues/19155比照) https://github.com/facebook/react/issues/19155
Just change the order of if block..只需更改 if 块的顺序..
Don't call Hooks inside loops, conditions, or nested functions.不要在循环、条件或嵌套函数中调用 Hook。 Instead, always use Hooks at the top level of your React function.
相反,始终在 React 函数的顶层使用 Hook。 You can follow the documentation here.
您可以按照此处的文档进行操作。
export default function(onClick) {
const element = useRef();
useEffect(() => {
if (element.current) {
element.current.addEventListener("click", onClick);
element.current.style.cursor = "pointer";
}
return () => {
if (element.current) {
element.current.removeEventListener("click", onClick);
}
};
}, []);
return element;
if (typeof onClick !== "function") {
return;
}
}
I ran into the same warning.我遇到了同样的警告。 It was because I had a condition similar to yours:
因为我有和你一样的情况:
if (typeof onClick !== "function") {
return;
}
above the hook.挂钩上方。
Because of this condition, the hook will not run every time.由于这种情况,钩子不会每次都运行。 That's where the warning is coming from.
这就是警告的来源。 I moved my condition after the hook and now everything is fine.
我在钩子后移动了我的条件,现在一切都很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.