由网友(心交朋友,钱交狗°)分享简介:props.location.pathname和props.match.url有什么区别在react-router-dom中?从他们的DOCS:https://reacttraining.com/react-router/web/api/locationmatch.url(字符串)URL的匹配部分。用于生成嵌套的...![小王小王几点了的博客 CSDN博客](https://p.xsw88.cn/allimgs/daicuo/20230903/2061.png)
props.location.pathname
和props.match.url
有什么区别
在react-router-dom
中?
![小王小王几点了的博客 CSDN博客](https://p.xsw88.cn/allimgs/daicuo/20230903/2061.png)
从他们的DOCS:https://reacttraining.com/react-router/web/api/location
match.url
(字符串)URL的匹配部分。用于生成嵌套的<Link>
%s
地点
用于匹配子元素而不是当前历史位置(通常为当前浏览器URL)的Location对象。
到目前为止,我只看到它们具有完全相同的值。
示例:
如果我的路由在此URL中匹配:
/search/searchValue?category=whatever
我想删除查询字符串并转到:
/search/searchValue
我应该使用一个而不是另一个,还是两个都能用?
推荐答案
location.pathname
表示根相对URL。
match.url
表示URL的匹配部分,因此可能是location.pathname
的一部分。
给定这两个组件:
function Home({match, location}) {
return (
<div>
{match.url}
<br/>
{location.pathname}
</div>
);
}
function App() {
return (
<Router>
<Route path="/" component={Home}/>
</Router>
);
}
如果您转到/something
,则
/
)
location.pathname将是/某个(相对根URL)
这是example on stackblitz。
在您的示例中,这取决于您的路由是否与准确的路径匹配(https://reacttraining.com/react-router/web/api/Route/exact-bool)。
如果不是这样(并且您只想检索/search/searchValue
),则应使用match.url
,因为location.pathname
可能大于/search/searchValue
->/search/searchValue/something
。
相关推荐
最新文章