cbd*_*per 13 javascript reactjs react-router react-router-v4 react-router-dom
什么之间的区别props.location.pathname和props.match.url
在react-router-dom?
从他们的文档:https : //reacttraining.com/react-router/web/api/location
匹配.url
(字符串)URL 的匹配部分。用于构建嵌套
<Link>s地点
用于匹配子元素而不是当前历史位置(通常是当前浏览器 URL)的位置对象。
到目前为止,我见过它们具有完全相同的值。
例子:
如果我的路线在这个网址中匹配:
/search/searchValue?category=whatever
我想删除查询字符串并转到:
/search/searchValue
我应该使用一个而不是另一个还是它们都可以工作?
Oli*_*ssé 11
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>
);
}
Run Code Online (Sandbox Code Playgroud)
如果你去/something,那么
/)这是关于 stackblitz的例子。
在您的示例中,这取决于您的路线是否与确切路径匹配(https://reacttraining.com/react-router/web/api/Route/exact-bool)。
如果情况并非如此(并且您只想检索/search/searchValue),那么您应该使用match.url因为location.pathname可能超过/search/searchValue-> /search/searchValue/something。
| 归档时间: |
|
| 查看次数: |
5228 次 |
| 最近记录: |