Reactjs中如何获取带有请求参数的完整路径?

How to obtain entire path with request parameters in Reactjs?

在 Reactjs 中,当我们使用 React Router 作为页面浏览的管理器时,我们会收到位置对象作为道具之一:

<Route path="/search" render={(props) => ( <SearchPage {...props} /> )} exact />

然后从组件内部(这里以SearchPage为例)获取路径如下:

var currentPathname = this.props.location.pathname;
console.log("Current pathname is: " + currentPathname);

输出:

Current pathname is: /search

但是我们是否有一个模式,其中存在 searchText 请求参数,例如:

 /search?searchText=NissanSilvia

然后仍然this.props.location.pathname只会产生:

 /search

如何获得包含所有当前请求参数的完整路径?

请使用location.pathname和location.search:

this.props.location.pathname+this.props.location.search

location.search returns 查询字符串

所以你可以这样做:

const {pathanme, search} = this.props.location
console.log(pathname + search)

以下值可用于位置对象 Location API Ref

{
  key: 'ac3df4', // not with HashHistory!
  pathname: '/somewhere'
  search: '?some=search-string',
  hash: '#howdy',
  state: {
    [userDefined]: true
  }
}

对于 URL 你正在寻找你可以使用 pathnamesearch 键,即

let { search, pathname } = this.location
console.log( pathname + search )