React Router DOM v6中matchPath路径匹配失败问题求助
React Router DOM v6 matchPath 匹配失败问题解决
问题根源:你的路径模式缺少开头的斜杠
/,React Router v6中matchPath匹配绝对路径时,模式必须以/开头,否则会被当作相对路径处理,无法匹配你提供的绝对路径/1031/account/12/list。正确的调用方式:
调整路径模式为带开头斜杠的格式,然后按如下方式调用matchPath:import { matchPath } from 'react-router-dom'; // 修正后的路径模式 const targetPath = '/:workspaceMasterStoreDataId?/account/:masterDataAccountId/list'; const currentPathname = "/1031/account/12/list"; // 基础调用方式 const matchResult = matchPath(targetPath, currentPathname); // 或者带配置项的调用(如需非精确匹配可设置 end: false) // const matchResult = matchPath({ // path: targetPath, // pathname: currentPathname, // end: true // 默认值为true,精确匹配路径末尾 // }); console.log(matchResult); // 此时会返回包含params的匹配对象: // { params: { workspaceMasterStoreDataId: '1031', masterDataAccountId: '12' }, ... }额外说明:你写的可选参数
:workspaceMasterStoreDataId?格式是正确的,支持参数存在或不存在的场景(比如/account/12/list也能匹配这个模式)。
内容的提问来源于stack exchange,提问作者Crocsx
相关产品推荐
相关产品推荐

