尝试仅根据索引路径过滤子路由。
在下面的示例中,一切正常但我们不希望输出中有任何属于/ab
的路由。
function getRoutes(path: string, routerData) {
return Object.keys(routerData).filter(routePath => {
console.log('routePath', routePath.indexOf(path));
return routePath.indexOf(path) === 0 && routePath !== path;
});
}
routerData = {
['/a']: {},
['/a/1]: {},
['/a/2]: {},
['/b/1]: {},
['/b/2]: {},
['/ab/2/1]: {},
}
期待结果
const result = ['/a/1', '/a/2'];
expect(getRoutes('/a', routerData).map(item => item.path)).toEqual(result);
Expected value to equal:
["/a/1", "/a/2"]
Received:
["/a/1", "/a/2", "/ab/2/1"]
答案 0 :(得分:0)
您的功能会匹配以/a
开头的所有路线,但不限于/a
。所以你也得到/a1
。
为避免这种情况,您需要检查所有以/a/
开头的路线:
function getRoutes(path: string, routerData) {
if (path[path.length-1] !== '/')
path += '/'; // Add a '/' to exclude incomplete paths
return Object.keys(routerData).filter(routePath => {
console.log('routePath', routePath.indexOf(path));
return routePath.indexOf(path) === 0; // This becomes useless: && routePath !== path;
});
}