首页 > 解决方案 > React Router: How to match indeterminate amount of sub paths of a nested route?

问题描述

I'm trying to create a file explorer like Dropbox. There will be an indeterminate amount of subpaths that look like this:

localhost:3001:file-manager/folder1/folder2/...folderN

I have this:

<Route path="/file-manager/:folderName" component={LandingPage} />

This allows me to visit: http://localhost:3001/file-manager/foo/bar/baz. However, when I check props.match I don't see it, it only shows a match for foo, not the levels below that (bar and baz).

match:
isExact: false
params: {folderName: "foo"}
path: "/file-manager/foo"
url: "/file-manager/foo"

How would I do this? All the tutorials I'm reading and watching about recursive routes append to the view. I want to replace the view.

标签: reactjsreact-router

解决方案


几个月前我遇到了完全相同的问题。我目前找不到我使用的确切代码,但如果我没记错的话,您可以使用星号来表示“从现在开始的所有内容”,其中包括任何进一步的路径分隔符:

<Route path="/file-manager/:folderName*" component={LandingPage} />

这确实意味着这props.match.params.folderName将是完整的字符串,因此/如果您需要一组路径组件,则必须自己拆分它。

重要提示:*将使它匹配任何东西,所以如果你有一个你想要匹配的特定路线,请确保你把它放在这个之前,例如

<Route path="/file-manager/example" component={ExamplePage} />
<Route path="/file-manager/:folderName*" component={LandingPage} />

推荐阅读