【问题标题】:How to route to or navigate to a route programmatically in nextjs class component?如何在 nextjs 类组件中以编程方式路由到或导航到路由?
【发布时间】:2021-01-22 05:49:08
【问题描述】:

我正在使用 nextjs 构建一个简单的应用程序。我的大部分组件都是功能组件。但是,我有一个类组件来处理表单。

我想在表单提交后重定向到主页。 console.log(this.router) 给出未定义。由于它是一个类组件,我不能使用useRouter() 钩子。如何在 next.js 的类组件中获取对路由器的引用?

【问题讨论】:

    标签: javascript reactjs next.js router


    【解决方案1】:

    我终于得到了答案,

    import Router from 'next/router'
    

    并使用Router.push(...)

    【讨论】:

      【解决方案2】:

      作为直接使用next/router 默认导出的替代方案,withRouter HOC 还可以将路由器对象添加到任何组件。

      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-26
        • 2017-09-27
        • 2023-04-06
        • 2019-07-27
        • 1970-01-01
        相关资源
        最近更新 更多