ReactJs中的嵌套URL路由

时间:2019-08-02 22:43:50

标签: javascript reactjs url-routing gatsby

要转到competition page,我正在Gatsby使用此功能,请转到该页面:

gatsby-node.js

exports.onCreatePage = async ({ page, actions }) => {
  const { createPage } = actions

  if (page.path.match(/^\/competition/)) {
    page.matchPath = "/competition/*"
    createPage(page)
  }
 }

我从competition page返回Game component

 return <Game path="/competition/:id" myid={ props.id }/>

然后在Game component内部,我正在渲染一个按钮以转到频道页面:

 <span className={style.button}>
     <Link to={'/competition/'+this.props.myid+'/'+rowdata['GameName']}/>
 </span>

在这里,我不知道如何去channel page,我在src/pages里面,并且像下面的代码一样保留我的网址:/competition/'+myid+'/'+GameName

我的方法正确吗? 我愿意接受其他解决方案

更新: 我可以接受这样的 url

<span className={style.button}>
     <Link to={'/competition/'+this.props.myid+'/channel'}/>
 </span>

1 个答案:

答案 0 :(得分:0)

我对gatsby并不熟悉,但是似乎您需要更严格地使用API​​根路径的正则表达式。

if (page.path.match(/^\/competition/)) {
    page.matchPath = "/competition/*"
    createPage(page)
  }

当前,以上匹配'/ competition','/ competition9302n','/ competition / 903n / channel'...基本上所有以'/ competition'开头的内容

如果要将'/ competition /'视为与'/ competition / some_id_here / channel'分开的路径,则需要定义两个(至少是更严格的根路径)不同的路径/路由。 / p>

例如。

if (page.path.match(/^\/competition\/[0-9a-z].*$/i)) { // this will match only '/competition/<some_id_here>'
    page.matchPath = "/competition/*"
    createPage(page)
  } else if (page.path.match(/^\/competition\/[0-9a-z].*\/channel$/i)) {//this will match only '/competition/<some_id_here>/channel'
  }