Difference between location.pathname and match.url in react-router-dom?(Reaction-Router-Dom中的Location.pathname和match.url有什么不同?)
问题描述
props.location.pathname
和props.match.url
有什么区别
在react-router-dom
中?
从他们的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
,则
- match.url将为/(因为URL的匹配部分为
/
) - 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
。
这篇关于Reaction-Router-Dom中的Location.pathname和match.url有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Reaction-Router-Dom中的Location.pathname和match.url有什么


- addEventListener 在 IE 11 中不起作用 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 失败的 Canvas 360 jquery 插件 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01