【问题标题】:How to obtain entire path with request parameters in Reactjs?如何在 Reactjs 中获取带有请求参数的完整路径?
【发布时间】:2019-07-14 12:05:13
【问题描述】:

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

<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

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

【问题讨论】:

    标签: javascript reactjs routing react-router


    【解决方案1】:

    location.search 返回查询字符串

    所以你可以这样做:

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

    【讨论】:

      【解决方案2】:

      以下值在位置对象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 )
      

      【讨论】:

        【解决方案3】:

        请使用 location.pathname 和 location.search:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-04-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多