react-router-dom中location.pathname和match.url的区别?

Difference between location.pathname and match.url in react-router-dom?

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

react-router-dom?

来自他们的文档:https://reacttraining.com/react-router/web/api/location

match.url

(string) The matched portion of the URL. Useful for building nested <Link>s

location

A location object to be used for matching children elements instead of the current history location (usually the current browser URL).

到目前为止,我只见过它们具有完全相同的值。

示例:

如果我的路线在这个url中匹配:

/search/searchValue?category=whatever

我想删除查询字符串并转到:

/search/searchValue

我应该用一个代替另一个,还是它们都可以工作?

location.pathname 表示 root 相对 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 将是 /something(相对根 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.