【问题标题】:how to access router params in getInitialProps stateles component in nextjs如何在 nextjs 的 getInitialProps 无状态组件中访问路由器参数
【发布时间】:2020-03-25 14:43:24
【问题描述】:

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

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

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

}

我该怎么做?!!!

【问题讨论】:

  • 您的idurlTitle 来自router,不是吗。你会在哪里打电话给Post.getInitialProps?另外为什么这个问题用react-hooks 标记?
  • @dev_junwen 是的,它们来自路由器,我想在 Post.getInitialProps 中使用它
  • 你在哪个地方打电话Post.getInitialProps
  • 在 Post 组件内部。 ts 像 next js doc exapmle (nextjs.org/learn/basics/fetching-data-for-pages/…) 但我想在 Post.getInitialProps 中使用路由器参数

标签: reactjs react-hooks next.js


【解决方案1】:

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

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

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


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

  const { id, title } = query

  return {
    id,
    urlTirle: title
  }

}

【讨论】:

    猜你喜欢
    • 2018-01-05
    • 1970-01-01
    • 2020-09-25
    • 2016-04-14
    • 1970-01-01
    • 2018-07-04
    • 2021-08-12
    • 2018-11-26
    • 1970-01-01
    相关资源
    最近更新 更多