首页 > 解决方案 > React, dynamically change part of a route

问题描述

I have read up on dynamic routes, but haven't found a solution that worked for me. I am working on a project where, when I click next, I want the routes to change as follows:

/part1/4
/part1/3
/part1/2
/part1/1
/part2/4
/part2/3
/part2/2
/part2/1
…
/part5/4
/part5/3
/part5/2
/part5/1

And of course if I click back, it should back through the routes.

I have this in App.js:

<Route path='/:part/:score' exact component={Questionnaire} />

But I'm not sure what I would need to put into the "to" part to change the /part1/ to part2, 3, 4, et.c at the appropriate time.

<Link to={`/part1/${scoreNum}`} id="next" onClick={this.disablePrevSelection} className={`btn btn-normal btn-green ${disabled}`}>Next &gt;</Link>

I apologize in advance if this is a simple question as I am new to ReactJs. Please let me know if anything else is needed.

Thank you!

标签: reactjsreact-router

解决方案


Your route should be like this:

<Route path='/path' component={Questionnaire} />

Note that we omitted exact here so that we can match every route starting with path

And link to it would be something like:

<Link to={`/part${partNum}/${scoreNum}`} id="next" onClick={this.disablePrevSelection} className={`btn btn-normal btn-green ${disabled}`}>Next &gt;</Link>

推荐阅读