简体   繁体   中英

Nested URL Routing in ReactJs

To go to, a competition page i'm using in Gatsby this function, to go to that page:

gatsby-node.js

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

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

from competition page i'm returning Game component :

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

then inside Game component i'm rendering a button to go to channel page:

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

here i don't know how to go to channel page i have inside src/pages and keeping my url like in the code: /competition/'+myid+'/'+GameName

is my approach correct? i'm open to other solutions

Update : i can accept a url like this:

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

I'm not familiar with gatsby, but it seems like you need to be stricter with the regexp of the root path of your API.

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

currently, the above matches '/competition', '/competition9302n', '/competition/903n/channel'... basically anything STARTING with '/competition'

If you want to treat '/competition/' as a separate path from '/competition/some_id_here/channel', then you need to define two (at the very least, a stricter root path) distinct paths/routes.

ex.

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'
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM