如何移除URL路径中的APP_ENTRY参数并消除多余斜杠
解决URL路径中多余斜杠的问题
问题出在路径拼接逻辑上:当前代码直接用${parentPath}/${configItem.name}拼接路径,当parentPath为空或configItem.name为空时,会产生连续斜杠(比如把APP_ENTRY设为空字符串后,父路径为空,拼接空name再加上子项home,就会得到//home)。
直接修改getPaths函数里的currentPath生成逻辑,就能消除多余斜杠:
const getPaths = (config: BasicConfig, parentPath: string = ""): Paths => config.reduce((paths, configItem) => { // 调整路径拼接逻辑,避免多余斜杠 let currentPath: string; if (!parentPath) { // 父路径为空时,直接使用当前项的name(空字符串则保持空) currentPath = configItem.name; } else if (!configItem.name) { // 当前项name为空时,直接使用父路径 currentPath = parentPath; } else { // 正常情况拼接父路径和当前name,中间加斜杠 currentPath = `${parentPath}/${configItem.name}`; } return { ...paths, ...(configItem.container ? { [configItem.container]: currentPath } : {}), ...{ [currentPath]: currentPath }, ...(configItem.name === LOGIN_ENTRY ? { LOGIN_ENTRY: currentPath } : {}), ...(configItem.name === APP_ENTRY ? { APP_ENTRY: currentPath } : {}), ...(configItem.children ? getPaths(configItem.children, currentPath) : {}) }; }, {} as Paths);
修改后验证效果:
- 当
const APP_ENTRY = ""时,生成的home路径为home,对应的URL是http://localhost:3000/home,可正常访问 - 当
const APP_ENTRY = "something-else"时,依然会生成something-else/home这样的正确路径,不影响原有功能
内容的提问来源于stack exchange,提问作者merlin
相关产品推荐
相关产品推荐

