如何将Next.js路由映射到props.url?

时间:2019-04-03 19:07:33

标签: reactjs next.js

README.md所示,我正在尝试访问this.props.url,但是它是未定义的,并且我不确定该组件应如何获得next-routes道具。我会期望有connectwithRouter等,但我从未见过props.url,也找不到import中提到的任何README.md

我应该如何获得this.props.url


enter image description here

2 个答案:

答案 0 :(得分:3)

您必须在getInitialProps中返回一个url对象,然后才能在render函数中访问该查询。

export default class Blog extends React.Component {
  static async getInitialProps ({ query }) {
    return { url: { query } }
  }
  render () {
    // this.props.url.query.slug
  }
}

答案 1 :(得分:1)

我觉得这是next-routes文档中的错字。该软件包已经几个月没有得到维护,并且尚未针对Next v7或更高版本进行更新。最后支持的是^ 6.0.0。

无论如何,在NextJS中,应该使用从withRouter导出的next/router HOC附加它。附加后,您的查询将存在于this.props.router.query上。