React:如何将路径与具体路径的参数进行比较
React: how to compare path with params witn concrete path
我有 2 个具有不同路径的 App 逻辑部分,我需要知道用户要去哪里。我这样做:
this.props.history.listen((location, action) =>
{
if (action === "PUSH")
{
const { modeType } = this.props;
if ((modeType === first && secondPathes.includes(location.pathname))
|| (modeType === second && firstPathes.includes(location.pathname)))
{
// some logic
}
}
});
但它不适用于带有参数的路径:"/customers/1/profile" != "/customers/:id/profile"
。如何正确比较路径?
解决方案是使用 react-router
中的 matchPath。
matchPath("/customers/3/profile", { path: "/customers/:id/profile" })
并使用 some
而不是 includes
。
我有 2 个具有不同路径的 App 逻辑部分,我需要知道用户要去哪里。我这样做:
this.props.history.listen((location, action) =>
{
if (action === "PUSH")
{
const { modeType } = this.props;
if ((modeType === first && secondPathes.includes(location.pathname))
|| (modeType === second && firstPathes.includes(location.pathname)))
{
// some logic
}
}
});
但它不适用于带有参数的路径:"/customers/1/profile" != "/customers/:id/profile"
。如何正确比较路径?
解决方案是使用 react-router
中的 matchPath。
matchPath("/customers/3/profile", { path: "/customers/:id/profile" })
并使用 some
而不是 includes
。