最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to route to or navigate to a route programmatically in nextjs class component? - Stack Overflow

programmeradmin0浏览0评论

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?

Share Improve this question edited Feb 2, 2023 at 6:38 Mayank Kumar Chaudhari asked Jan 22, 2021 at 5:49 Mayank Kumar ChaudhariMayank Kumar Chaudhari 18.9k13 gold badges72 silver badges155 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

Finally 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)
发布评论

评论列表(0)

  1. 暂无评论