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

Ely*_*edy 4 reactjs next.js react-hooks

我使用 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

}
Run Code Online (Sandbox Code Playgroud)

我该怎么做 ?!!!

Ale*_*chi 9

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

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

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


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

  const { id, title } = query

  return {
    id,
    urlTirle: title
  }

}
Run Code Online (Sandbox Code Playgroud)