Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
858 views
in Technique[技术] by (71.8m points)

reactjs - Multiple params with React Router

I use React 15.0.2 and React Router 2.4.0. I want to pass multiple params to my route and I'm not sure how to do it in the best way:

<Route name="User" path="/user" component={UserPage}>   
    <Route name="addTaskModal" path="/user/manage:id" component={ManageTaskPage} />
</Route>

And what is want is something like:

 <Route name="User" path="/user" component={UserPage}>  
    <Route name="addTaskModal" path="/user/manage:id:type" component={ManageTaskPage} />
</Route>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As @alexander-t mentioned:

path="/user/manage/:id/:type"

If you want to keep them optional:

path="/user/manage(/:id)(/:type)"

React Router v4

React Router v4 is different than v1-v3, and optional path parameters aren't explicitly defined in the documentation.

Instead, you are instructed to define a path parameter that path-to-regexp understands. This allows for much greater flexibility in defining your paths, such as repeating patterns, wildcards, etc. So to define a parameter as optional you add a trailing question-mark (?).

So, to define optional parameters, you can do:

path="/user/manage/:pathParam1?/:pathParam2?"

i.e.

<Route path="/user/manage/:pathParam1?/:pathParam2?" component={MyPage} />

Whereas, The mandatory Parameters are still same in V4:

path="/user/manage/:id/:type"

To access PathParam's value, you can do :

this.props.match.params.pathParam1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...