Reaction-Router-Dom中的Location.pathname和match.url有什么不同?有什么不同、Dom、Router、Reaction

由网友(心交朋友,钱交狗°)分享简介:props.location.pathname和props.match.url有什么区别在react-router-dom中?从他们的DOCS:https://reacttraining.com/react-router/web/api/locationmatch.url(字符串)URL的匹配部分。用于生成嵌套的...

props.location.pathnameprops.match.url有什么区别

react-router-dom中?

小王小王几点了的博客 CSDN博客

从他们的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

阅读全文

相关推荐

最新文章