javascript - NextJS useRouter 在函数体内使用时出错
问题描述
我希望这是一个简单的问题。我不明白它为什么这样做。无论如何,使用 NextJS,我正在尝试使用 useRouter 挂钩访问路由器中的参数,并将其与 querystring 插件组合以拆分 asPath,因为如果使用无状态,NextJS 不允许您访问路由器的查询部分。这是我的代码:
import { useRouter } from 'next/router';
import queryString from "query-string";
const withPageRouter = (router) => {
router.query = { ...queryString.parse(router.asPath.split(/\?/)[1]) };
return router;
};
function getRouterParams(){
const router = useRouter();
router = withPageRouter(router);
return router;
}
export async function getTown() {
const town = await getRouterParams();
return town;
}
现在,当我尝试运行它时,出现此错误:
Server Error
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
lib/api.js (34:26) @ getRouterParams
32 |
33 | function getRouterParams(){
> 34 | const router = useRouter();
| ^
35 | router = withPageRouter(router);
36 | return router;
37 | }
但对我来说,它看起来应该没问题;它在函数体中吗?我觉得我错过了一些明显的东西。我很感激帮助。
解决方案
您不能在正常功能中调用 useRouter() 。
您只能在 React 函数组件或自定义钩子的顶部调用 useRouter()
在此处了解有关 Hooks 规则的更多信息:https ://reactjs.org/docs/hooks-rules.html
推荐阅读
- arcgis - 为 Web 应用程序构建器添加自定义小部件 (ArcGIS Enterprise)
- firebase - Firebase 云功能中的 Firebase 存储错误
- javascript - 使用 CSS 使 div 的内容滚动到底部
- java - Android Studio 项目出现错误“缺少权限”
- mysql - 通过 perl DBI 从主机连接到在容器中运行的 mysql
- jspdf - jsPDF:如何添加和/或对齐两个不同的表格(并排)
- python - 按下按钮后突出显示按钮边框 tkinter
- php - 如何在htaccess中处理具有相同文件名的两个不同参数?
- amazon-web-services - 您可以复制特定的 AWS ECR 存储库吗?
- c# - C# 处理 UI 自动化文本选择事件