问题
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