gpt4 book ai didi

javascript - react 路由器: save an extended path as a route param

转载 作者:太空宇宙 更新时间:2023-11-04 16:13:05 25 4
gpt4 key购买 nike

我想要一条如下所示的路径:

/projects/:projectId/:folder1/:folder2/.../:folderN/:currentFolder/

其中 projectId 将是单个字符串,如 1,而 folder1,folder2, ...,folderN 来自于分割路径那个位置。

所以像这样的正则表达式可以完全匹配它:

/\/?projects\/(\w|\d)+\/folders\/((\w|\d)*\/?)*(\w|\d)+\/?/;

但是,我无法将当前文件夹之前的文件夹路径保存为路由中的参数。也就是说,我可以获得类似 :projectId:currentFolder 的内容,但我想将通向当前文件夹的文件夹列表保存为 :path 或者其他什么。

在React Router中保存这个任意路径的语法是什么?

最佳答案

参数仅匹配URL segments .

对于不确定数量的文件夹,除了具有 N 条路线(其中 N 是已知的可能文件夹的最大数量)之外,没有实用的方法可以使用参数来执行此操作)。当然,这样做会很乏味,并且如果 N 在不添加更多路由的情况下不断增加,就会中断。

最好的办法是使用通配符运算符来匹配所有文件夹,然后在需要访问文件夹的任何位置对 params.splat 值进行字符串拆分。

<Route path=":productId/**/:currentFolder" component={Folder} />

给定路径名:/17/this/is/the/path/to/the/folder

const Folder = ({ params }) => {
const { productId, splat, currentFolder } = params
const folders = splat.split('/')
// productId = '17'
// currentFolder = 'folder'
// folders = ['this', 'is', 'the', 'path', 'to', 'the']
...
}

关于javascript - react 路由器: save an extended path as a route param,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41304969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com