如何使用“useRouter()"来自类组件中的 next.js? [英] How to use "useRouter()" from next.js in a class component?
问题描述
我试图通过使用next/router"中的 useRouter()
从我的 url 模式中获取查询,例如 localhost:3000/post?loc=100
使用该 ID 从我的服务器获取一些数据.当我在无状态功能组件中使用它时,它起作用了.
I was trying to get the queries from my url pattern like localhost:3000/post?loc=100
by using useRouter()
from "next/router" and fetching some data using that id from my server. It worked when I used it in a Stateless Functional Component.
然后页面显示无效的钩子调用".我尝试调用无状态功能组件的 getInitalProps()
,但它也没有在那里工作并显示相同的错误.使用这种方法有什么规律吗?
But the page showing "Invalid hook call" then. I tried calling getInitalProps()
of a Stateless Functional Component, but it didn't work there either and showed the same error.
Is there any rule to use this method?
我正在使用 React 库和 Next.js 框架开发前端.
I was developing a front-end using React Library and Next.js Framework.
constructor(props) {
this.state = {
loc: useRouter().query.loc,
loaded: false
};
}
推荐答案
Hooks 只能在功能组件内部使用,不能在类内部使用.根据 next.js 文档,我建议使用 withRouter HOC:
Hooks can be used only inside functional components, not inside classes. I would recommend to use withRouter HOC as per next.js documentation:
使用 useRouter
钩子,或者 withRouter
用于类组件.
use the
useRouter
hook, orwithRouter
for class components.
或者查看从类到钩子,如果你想切换到钩子.
Or see From Classes to Hooks if you want to switch to hooks.
const MyClassWithRouter = (props) => {
const router = useRouter()
return <MyClass {...props} router={router} />
}
class MyClass...
constructor(props) {
this.state = {
loc: props.router.query.loc,
loaded: false
};
}
这篇关于如何使用“useRouter()"来自类组件中的 next.js?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!