I am building a simple app using nextjs. most of my ponents are functional ponents. However, I have a class ponent to handle form.
I want to redirect to the home page after the form is submitted. console.log(this.router)
gives undefined. Since it is a class ponent I can't use useRouter()
hook. How do I get reference to router in class ponents in next.js?
I am building a simple app using nextjs. most of my ponents are functional ponents. However, I have a class ponent to handle form.
I want to redirect to the home page after the form is submitted. console.log(this.router)
gives undefined. Since it is a class ponent I can't use useRouter()
hook. How do I get reference to router in class ponents in next.js?
2 Answers
Reset to default 7Finally I got the answer,
import Router from 'next/router'
and use Router.push(...)
With Next 13 onwards, import router from next/navigation
As an alternative to using the next/router
default export directly, withRouter
HOC can also add the router object to any ponent.
import * as React from 'react'
import { withRouter } from 'next/router'
class Page extends React.Component {
render() {
const { router } = this.props
return <p>{router.pathname}</p>
}
}
export default withRouter(Page)
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745107744a4611659.html
评论列表(0条)