How to use "useRouter()" from next.js in a class component?

Sha*_*san 22 javascript routing reactjs next.js react-hooks

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.

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?

I was developing a front-end using React Library and Next.js Framework.

constructor(props) {
  this.state = {
    loc: useRouter().query.loc,
    loaded: false
  };
}
Run Code Online (Sandbox Code Playgroud)

Apr*_*ion 27

钩子只能在功能组件内部使用,不能在类内部使用。我建议按照 next.js 文档使用withRouter HOC:

使用useRouter钩子,或withRouter用于类组件。

或者如果您想切换到钩子,请参阅从类到钩子。


一般来说,可以创建一个包装函数组件来通过 props 将自定义钩子传递到类组件中(但在这种情况下没有用):
const MyClassWithRouter = (props) => {
  const router = useRouter()
  return <MyClass {...props} router={router} />
}

class MyClass...
  constructor(props) {
    this.state = {
      loc: props.router.query.loc,
      loaded: false
    };
  }
Run Code Online (Sandbox Code Playgroud)

  • 新链接:https://nextjs.org/docs/api-reference/next/router#withrouter 因为自述文件的链接已[过时](https://github.com/vercel/next.js/tree/78775954f2384d75f8ba0a2775cfcf7e5a50f355#using -高阶组件) (2认同)

Cir*_*四事件 8

withRouter例子

/sf/answers/3992032271/提到了它,但像我这样的新手需要更多细节。更详细/直接的描述是:

功能组件:

import { useRouter } from "next/router";

export default function Post() {
  const router = useRouter();
  return (
    <div>{ router.query.id }</div>
  )
}
Run Code Online (Sandbox Code Playgroud)

类组件等效:

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>
    )
  }
})
Run Code Online (Sandbox Code Playgroud)

我对此进行了更具体的测试,如下所示。首先,我将vercel/next-learn-starter/basics-final/pages/posts/[id].js其破解以使用路由器:

diff --git a/basics-final/pages/posts/[id].js b/basics-final/pages/posts/[id].js
index 28faaad..52954d3 100644
--- a/basics-final/pages/posts/[id].js
+++ b/basics-final/pages/posts/[id].js
@@ -4,13 +4,17 @@ import Head from 'next/head'
 import Date from '../../components/date'
 import utilStyles from '../../styles/utils.module.css'
 
+import { useRouter } from "next/router"
+
 export default function Post({ postData }) {
+  const router = useRouter();
   return (
     <Layout>
       <Head>
         <title>{postData.title}</title>
       </Head>
       <article>
+        <div>router.query.id = {router.query.id}</div>
         <h1 className={utilStyles.headingXl}>{postData.title}</h1>
         <div className={utilStyles.lightText}>
           <Date dateString={postData.date} />
Run Code Online (Sandbox Code Playgroud)

然后,我将其运行为:

git clone https://github.com/vercel/next-learn-starter
cd next-learn-starter
git checkout 5c2f8513a3dac5ba5b6c7621d8ea0dda881235ea
cd next-learn-starter
npm install
npm run dev
Run Code Online (Sandbox Code Playgroud)

现在,当我访问:http://localhost:3000/posts/ssg-ssr 时,我看到:

router.query.id = ssg-ssr
Run Code Online (Sandbox Code Playgroud)

然后我将其转换为等效的类:

import Layout from '../../components/layout'
import { getAllPostIds, getPostData } from '../../lib/posts'
import Head from 'next/head'
import Date from '../../components/date'
import utilStyles from '../../styles/utils.module.css'

import { withRouter } from 'next/router'
import React from "react"


export default withRouter(class extends React.Component {
  render() {
    return (
      <Layout>
        <Head>
          <title>{this.props.postData.title}</title>
        </Head>
        <article>
          <div>router.query.id = {this.props.router.query.id}</div>
          <h1 className={utilStyles.headingXl}>{this.props.postData.title}</h1>
          <div className={utilStyles.lightText}>
            <Date dateString={this.props.postData.date} />
          </div>
          <div dangerouslySetInnerHTML={{ __html: this.props.postData.contentHtml }} />
        </article>
      </Layout>
    )
  }
})

export async function getStaticPaths() {
  const paths = getAllPostIds()
  return {
    paths,
    fallback: false
  }
}

export async function getStaticProps({ params }) {
  const postData = await getPostData(params.id)
  return {
    props: {
      postData
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

一切似乎都没有改变。

在 Next.js 10.2.2 上测试。