在Layout组件配置onMenuHeaderClick事件遇到问题
来源:9-2 PC 管理端:使用 ProLayout 组件搭建菜单(下)

是李骏同学
2023-09-15
[plugin:vite-plugin-eslint] C:\Users\Adam\WorkSpace\water-drop-pc\src\components\Layout\index.tsx
17:15 error React Hook "useNavigate" is called in function "menuHeaderClickHandler" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use" react-hooks/rules-of-hooks
✖ 1 problem (1 error, 0 warnings)
C:/Users/Adam/WorkSpace/water-drop-pc/src/components/Layout/index.tsx
at formatError (file:///C:/Users/Adam/WorkSpace/water-drop-pc/node_modules/.pnpm/vite@3.2.0_less@4.1.3/node_modules/vite/dist/node/chunks/dep-61d2428a.js:42899:46)
at TransformContext.error (file:///C:/Users/Adam/WorkSpace/water-drop-pc/node_modules/.pnpm/vite@3.2.0_less@4.1.3/node_modules/vite/dist/node/chunks/dep-61d2428a.js:42895:19)
at TransformContext.transform (file:///C:/Users/Adam/WorkSpace/water-drop-pc/node_modules/.pnpm/vite-plugin-eslint@1.8.1_eslint@8.28.0_vite@3.2.0/node_modules/vite-plugin-eslint/dist/index.mjs:1:1989)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Object.transform (file:///C:/Users/Adam/WorkSpace/water-drop-pc/node_modules/.pnpm/vite@3.2.0_less@4.1.3/node_modules/vite/dist/node/chunks/dep-61d2428a.js:43148:30)
at async loadAndTransform (file:///C:/Users/Adam/WorkSpace/water-drop-pc/node_modules/.pnpm/vite@3.2.0_less@4.1.3/node_modules/vite/dist/node/chunks/dep-61d2428a.js:39539:29
Click outside or fix the code to dismiss.
You can also disable this overlay by setting server.hmr.overlay to false in vite.config.js.
在网上搜索的内容,归因是这个api不该在Layout这个层级去写,或者使用内嵌的写法,于是把逻辑提取了出来,问题依旧。不知道该怎么解决
const menuHeaderClickHandler = () => {
// window.location.href = '/';
const nav = useNavigate();
nav('/');
};
写回答
1回答
-
hooks不能在普通函数里调用,只能在自定义hook和函数组件顶层调用
//函数组件 const Layout = () => { const nav = useNavigate(); const menuHeaderClickHandler = () => { nav('/'); }; //... } export default Layout;
122023-09-17
相似问题