![](/img/trans.png)
[英]How do you access react hooks in multiple components? What am I doing wrong with my react hook?
[英]Trouble with React Hooks, which react hook rule am I breaking?
我收到此错误:
无效的挂钩调用。 钩子只能在 function 组件的主体内部调用。
我正在使用钩子通过 function HeaderView()
(单独工作正常)并设置 state 来获取路由器位置,以便我可以根据当前路由使用我的组件。
这是我的钩子的组成:
const Navbar = () => {
const [route, setRoute] = useState("/");
function HeaderView() {
let location = useLocation();
console.log(location.pathname);
setRoute(location.pathname);
return;
}
useEffect(() => {
HeaderView()
}, [route]);
.. rest of the component.
useLocation 是“react-router-dom”提供的 function; 每次我认为我掌握了钩子时,似乎还有其他东西让我绊倒,所以很沮丧,感谢阅读。
如果打开HeaderView
会发生什么?
const Navbar = () => {
const [route, setRoute] = useState("/");
let location = useLocation();
useEffect(() => {
console.log(location.pathname);
setRoute(location.pathname);
}, [location]);
.. rest of the component.
不要在循环、条件或嵌套函数中调用 Hook。 相反,请始终在 React function 的顶层使用 Hooks。 通过遵循此规则,您可以确保每次组件呈现时都以相同的顺序调用 Hook。 这就是允许 React 在多个
useState
和useEffect
调用之间正确保留 Hooks 的 state 的原因。
注意:另外,请注意useEffect
中的无限循环。
我认为您看到该错误是因为您在 useEffect 中调用了钩子。
Do not call Hooks inside functions passed to useMemo, useReducer, or useEffect.
来源: https://reactjs.org/warnings/invalid-hook-call-warning.html
钩子的规则之一是它们不能在循环、条件或嵌套函数中调用。 相反,请始终在 React function 的顶层使用 Hooks。
https://reactjs.org/docs/hooks-rules.html
有一篇很好的文章,解释了如何通过闭包实现挂钩的概念。 我喜欢阅读它,它帮助我更好地理解它是如何工作的
https://www.netlify.com/blog/2019/03/11/deep-dive-how-do-react-hooks-really-work/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.