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

作为useRouter的替代品,您可能希望使用withRouter(可用于类组件)。参见以下相关SO问题:

如何使用useRouter()"从next.js在一个类组件?

import { withRouter } from 'next/router'
import React from "react";
export default withRouter(class extends React.Component {
render() {
return (
<div>{ this.props.router.query.id }</div>
)
}
})

相关内容

最新更新