首页 > 解决方案 > React Hooks 有问题,我打破了哪个 React Hook 规则?

问题描述

我收到此错误:

无效的挂钩调用。钩子只能在函数组件的主体内部调用。

我正在使用钩子来获取具有功能HeaderView()(单独工作正常)和设置状态的路由器位置,以便我可以根据当前路由使用我的组件。

这是我的钩子的组成:

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”提供的功能;每次我认为我掌握了钩子时,似乎还有其他东西让我绊倒,所以很沮丧,感谢阅读。

标签: javascriptreactjsreact-hooks

解决方案


如果你打开包装会发生什么HeaderView

const Navbar = () => {
const [route, setRoute] = useState("/");
let location = useLocation();

useEffect(() => {
    console.log(location.pathname);
    setRoute(location.pathname);
}, [location]);

.. rest of the component.

仅在顶层调用 Hooks

不要在循环、条件或嵌套函数中调用 Hook。相反,请始终在 React 函数的顶层使用 Hooks。通过遵循此规则,您可以确保每次渲染组件时都以相同的顺序调用 Hook。这就是允许 React 在多个useStateuseEffect调用之间正确保留 Hooks 状态的原因。

注意:另外,请注意useEffect.


推荐阅读