Reaction-Router-Dom中的Location.pathname和match.url有什么不同? [英] Difference between location.pathname and match.url in react-router-dom?

查看:0
本文介绍了Reaction-Router-Dom中的Location.pathname和match.url有什么不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

props.location.pathnameprops.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有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆