javascript - 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”提供的功能;每次我认为我掌握了钩子时,似乎还有其他东西让我绊倒,所以很沮丧,感谢阅读。
解决方案
如果你打开包装会发生什么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 在多个
useState
和useEffect
调用之间正确保留 Hooks 状态的原因。
注意:另外,请注意useEffect
.
推荐阅读
- c# - 如何使用 LIST 进行过滤
在 LINQ 中 - networking - What can be done to avoid hosts file entry?
- node.js - Import Express Routes causes Request Body to be Undefined
- windows - no sound difference with multiband compression plugin juce
- perl - 从 perl 脚本运行时,无法获取 wget 命令以将响应结果输出到文件
- python-3.x - 仅将有效的 DAG 文件移动到 Cloud Composer
- django - Django注释返回重复条目
- vue.js - 将 jwt 令牌存储在 nuxt js 中的 cookie 中是一个最佳选择,因为 ssr 不支持本地存储
- javascript - Vue3 Google Maps 标记无法移除
- selenium - 获取“主要”java.lang.Error:未解决的编译问题“错误