Allow slashes in route parameter on React

我的梦境 提交于 2021-01-27 04:09:41

问题


I have a router like this:

<Route path="/blog/:date/:folder" render={(props: any) => <Home />

It works with this:

http://localhost/blog/2017-05-20/test

However, :folder can have slashes (sub-dir) and i want to parse all path at once in folder.

This is not working:

http://localhost/blog/2017-05-20/test/sub/dir

In this situation, I only get test. I want to get :folder as test/sub/dir as a whole.

Is there any way to achieve this with React Router?

Expected:

:date => '2017-05-20'
:folder => 'test/sub/dir'

Actual:

:date => '2017-05-20'
:folder => 'test'

回答1:


Yes, you can do this by adding a + to your Route path. So, like this:

<Route path="/blog/:date/:folder+" ... />

This library is being used for matching the path. So for more advanced matching cases this is a better place to look at then the React Router docs.




回答2:


You can recursively embed components if they're rendered by a Route - you could then check this.props.match for a path name, for example, in your base Router, you'd have the basic route, /blog/:date, which renders a Home component.

Then inside the Home component, you could render another Route (it still works from here, despite not being an immediate child of the Router) with a set up like

<Route path={`${this.props.match.url}/:folder`} component={Folder} />

Then inside the Folder component you would render the same Route, which will progressively render sub-components for each /:folder in the path.

The match object also includes isExact which you could use to determine if you're on the last level of the folder structure from the URL.

Source: See this example of embedded routes.



来源:https://stackoverflow.com/questions/56133182/allow-slashes-in-route-parameter-on-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!