英文:
How to make an endless route?
问题
如何创建一个无限嵌套的路由?
我有一个未知的嵌套结构,需要在路由中显示它,例如:
文件夹 url.com/folder
-子文件夹 1 url.com/folder/child1
--子文件夹 2 url.com/folder/child1/child2
---子文件夹 3 url.com/folder/child1/child2/child3
----子文件夹 4 url.com/folder/child1/child2/child3/child4
...
<Route path="folder">
<ComponentExample />
</Route>
如果嵌套结构未知,如何确定路由呢?
英文:
How to make an endless route?
I have an unknown nesting, following which we need to display it in the route, for example
Folder url.com/folder
-Child 1 url.com/folder/child1
--Child 2 url.com/folder/child1/child2
---Child 3 url.com/folder/child1/child2/child3
---- Child 4 url.com/folder/child1/child2/child3/child4
...
<Route path="folder">
<ComponentExample />
</Route>
How to determine the route if the nesting is unknown?
答案1
得分: 1
使用当前段,例如"directory",后跟"*"
通配符,表示该段后的任何内容也可以匹配。
const RootComponent = {
...
return (
<Routes>
...
<Route path="/folder/*" element={<ComponentExample />} />
...
</Routes>
);
};
然后,该路由组件会相对于此父路径渲染子路径。
const ComponentExample = () => {
...
return (
<Routes>
...
<Route path="child1/*" element={<Child1 />} /> // <-- "/folder/child1/*
...
</Routes>
);
};
依此类推,直到最终到达不再渲染另一组子路径的叶节点。
如果您只想为任何"/folder/*"
渲染相同的ComponentExample
,则可以将此作为路径,并使用splat获取其余路径。
const RootComponent = {
...
return (
<Routes>
...
<Route path="/folder/*" element={<ComponentExample />} />
...
</Routes>
);
};
import { useParams } from 'react-router-dom';
const ComponentExample = () => {
const { "*": splat } = useParams();
console.log(splat); // "child1", "child1/child2", "child1/child2/child3", 等等
...
return (
...
);
};
英文:
Use the current segment, e.g. "directory", followed by the "*"
wildcard character to indicate that anything after the segment can also be matched.
const RootComponent = {
...
return (
<Routes>
...
<Route path="/folder/*" element={<ComponentExample />} />
...
</Routes>
);
};
This routed component then renders descendent routes relative to this parent path.
const ComponentExample = () => {
...
return (
<Routes>
...
<Route path="child1/*" element={<Child1 />} /> // <-- "/folder/child1/*
...
</Routes>
);
};
And so on until you finally reach a leaf node that doesn't render another set of descendent routes.
If you just intend to render this same ComponentExample
for any "/folder/*
then you can use just this as the path and use the splat to get the rest of the path.
const RootComponent = {
...
return (
<Routes>
...
<Route path="/folder/*" element={<ComponentExample />} />
...
</Routes>
);
};
import { useParams } from 'react-router-dom';
const ComponentExample = () => {
const { "*": splat } = useParams();
console.log(splat); // "child1", "child1/child2", "child1/child2/child3", etc
...
return (
...
);
};
答案2
得分: 0
如果你正在使用 react-router-dom v5+,只需设置 path=folder/*,路由器将匹配以 folder/ 开头的每个路由。
英文:
If you are using react-router-dom v5+, just set path=folder/*, the router will match every route starting with folder/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论