如何在 nextjs 的 getInitialProps stateles 组件中访问路由器参数

how to access router params in getInitialProps stateles component in nextjs

我在使用 nextjs,在使用 getInitialProps 时遇到问题。

我想在 getInitialProps 中使用我在 Post 组件中创建的变量。 你可以看到我的男女同校:

const Post = props => {
  const router = useRouter()
   let id = router.query.id  
   let urlTitle = router.query.title

  return (
    <Layout>
       //somthing
    </Layout>
  )
}


Post.getInitialProps = async () => {

// i want to use {id} and {urlTitle} here

}

我该怎么做?!!!

您应该能够从 getInitialProps 访问{query}

const Post = ({id, urlTitle}) => {

  return (
    <Layout>
       //somthing
    </Layout>
  )
}


Post.getInitialProps = async ({ query }) => {

  const { id, title } = query

  return {
    id,
    urlTirle: title
  }

}