Javascript 从 react-router 哈希片段获取查询参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29852998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:07:32  来源:igfitidea点击:

Getting query parameters from react-router hash fragment

javascriptreactjsclient-sidereact-routerclient-side-scripting

提问by Christopher Robin

I'm using react and react-router for my application on the client side. I can't seem to figure out how to get the following query parameters from a url like:

我在客户端为我的应用程序使用 react 和 react-router 。我似乎无法弄清楚如何从 url 获取以下查询参数,例如:

http://xmen.database/search#/?status=APPROVED&page=1&limit=20

My routes look like this (the path is totally wrong I know):

我的路线看起来像这样(我知道路径完全错误):

var routes = (
<Route>
    <DefaultRoute handler={SearchDisplay}/>
    <Route name="search" path="?status=:status&page=:page&limit=:limit" handler={SearchDisplay}/>
    <Route name="xmen" path="candidate/:accountId" handler={XmenDisplay}/>
</Route>
);

My route is working fine but I'm just not sure how to format the path to get the parameters I want. Appreciate any help on this!

我的路线工作正常,但我不确定如何格式化路径以获取我想要的参数。感谢您对此的任何帮助!

回答by Duncan Finney

Note: Copy / Pasted from comment. Be sure to like the original post!

注意:从评论中复制/粘贴。一定要喜欢原帖!

Writing in es6 and using react 0.14.6 / react-router 2.0.0-rc5. I use this command to lookup the query params in my components:

用 es6 编写并使用 react 0.14.6 / react-router 2.0.0-rc5。我使用此命令在我的组件中查找查询参数:

this.props.location.query

It creates a hash of all available query params in the url.

它在 url 中创建所有可用查询参数的哈希。

Update:

更新:

For React-Router v4, see this answer. Basically, use this.props.location.searchto get the query string and parse with the query-stringpackage or URLSearchParams:

对于 React-Router v4,请参阅此答案。基本上,用于this.props.location.search获取查询字符串并使用query-string包或URLSearchParams 进行解析:

const params = new URLSearchParams(paramsString); 
const tags = params.get('tags');

回答by Marrs

OLD (pre v4):

旧(v4 之前):

Writing in es6 and using react 0.14.6 / react-router 2.0.0-rc5. I use this command to lookup the query params in my components:

用 es6 编写并使用 react 0.14.6 / react-router 2.0.0-rc5。我使用此命令在我的组件中查找查询参数:

this.props.location.query

It creates a hash of all available query params in the url.

它在 url 中创建所有可用查询参数的哈希。

UPDATE (React Router v4+):

更新(反应路由器 v4+):

this.props.location.query in React Router 4 has been removed (currently using v4.1.1) more about the issue here: https://github.com/ReactTraining/react-router/issues/4410

React Router 4 中的 this.props.location.query 已被删除(目前使用 v4.1.1)更多关于这里问题的信息:https: //github.com/ReactTraining/react-router/issues/4410

Looks like they want you to use your own method to parse the query params, currently using this library to fill the gap: https://github.com/sindresorhus/query-string

看起来他们希望你使用自己的方法来解析查询参数,目前使用这个库来填补空白:https: //github.com/sindresorhus/query-string

回答by hashcode55

The above answers won't work in react-router v4. Here's what I did to solve the problem -

以上答案在react-router v4. 这是我为解决问题所做的工作-

FirstInstall query-stringwhich will be required for parsing.

首先安装解析所需的查询字符串

npm install -save query-string

npm install -save query-string

Nowin the routed component you can access the un-parsed query string like this

现在在路由组件中,您可以像这样访问未解析的查询字符串

this.props.location.search

this.props.location.search

You can cross check it by logging in the console.

您可以通过登录控制台进行交叉检查。

Finallyparse to access the query parameters

最后解析访问查询参数

const queryString = require('query-string');
var parsed = queryString.parse(this.props.location.search);
console.log(parsed.param); // replace param with your own 

So if query is like ?hello=world

所以如果查询就像 ?hello=world

console.log(parsed.hello)will log world

console.log(parsed.hello)会登录 world

回答by slideshowp2

update 2017.12.25

更新 2017.12.25

"react-router-dom": "^4.2.2"

"react-router-dom": "^4.2.2"

url like

网址喜欢

BrowserHistory: http://localhost:3000/demo-7/detail/2?sort=name

BrowserHistoryhttp://localhost:3000/demo-7/detail/2?sort=name

HashHistory: http://localhost:3000/demo-7/#/detail/2?sort=name

HashHistoryhttp://localhost:3000/demo-7/#/detail/2?sort=name

with query-stringdependency:

具有查询字符串依赖性:

this.id = props.match.params.id;
this.searchObj = queryString.parse(props.location.search);
this.from = props.location.state.from;

console.log(this.id, this.searchObj, this.from);

results:

结果:

2 {sort: "name"} home

2 {sort: "name"} home



"react-router": "^2.4.1"

"react-router": "^2.4.1"

Url like http://localhost:8080/react-router01/1?name=novaline&age=26

网址喜欢 http://localhost:8080/react-router01/1?name=novaline&age=26

const queryParams = this.props.location.query;

const queryParams = this.props.location.query;

queryParams is a object contains the query params: {name: novaline, age: 26}

queryParams 是一个包含查询参数的对象: {name: novaline, age: 26}

回答by EsterlingAccime Youtuber

With stringquery Package:

使用 stringquery 包:

import qs from "stringquery";

const obj = qs("?status=APPROVED&page=1limit=20");  
// > { limit: "10", page:"1", status:"APPROVED" }

With query-string Package:

使用查询字符串包:

import qs from "query-string";
const obj = qs.parse(this.props.location.search);
console.log(obj.param); // { limit: "10", page:"1", status:"APPROVED" } 

No Package:

无套餐:

const convertToObject = (url) => {
  const arr = url.slice(1).split(/&|=/); // remove the "?", "&" and "="
  let params = {};

  for(let i = 0; i < arr.length; i += 2){
    const key = arr[i], value = arr[i + 1];
    params[key] = value ; // build the object = { limit: "10", page:"1", status:"APPROVED" }
  }
  return params;
};


const uri = this.props.location.search; // "?status=APPROVED&page=1&limit=20"

const obj = convertToObject(uri);

console.log(obj); // { limit: "10", page:"1", status:"APPROVED" }


// obj.status
// obj.page
// obj.limit

Hope that helps :)

希望有帮助:)

Happy coding!

快乐编码!

回答by Meisam Nazari

"react-router-dom": "^5.0.0",

you do not need to add any additional module just in your component that has a url address like this:

您无需在具有如下 url 地址的组件中添加任何其他模块:

http://localhost:3000/#/?authority'

http://localhost:3000/#/?authority'

you can try the following simple code:

您可以尝试以下简单代码:

    const search =this.props.location.search;
    const params = new URLSearchParams(search);
    const authority = params.get('authority'); //

回答by Adam McCormick

After reading the other answers (First by @duncan-finney and then by @Marrs) I set out to find the change log that explains the idiomatic react-router 2.x way of solving this. The documentation on using location(which you need for queries) in components is actually contradicted by the actual code. So if you follow their advice, you get big angry warnings like this:

在阅读了其他答案(首先是@duncan-finney,然后是@Marrs)之后,我开始查找更改日志,该日志解释了解决此问题的惯用 react-router 2.x 方法。在组件中使用位置(您需要查询)的文档实际上与实际代码相矛盾。所以,如果你听从他们的建议,你会收到这样的愤怒警告:

Warning: [react-router] `context.location` is deprecated, please use a route component's `props.location` instead.

It turns out that you cannot have a context property called location that uses the location type. But you can use a context property called loc that uses the location type. So the solution is a small modification on their source as follows:

事实证明,您不能拥有使用位置类型的名为 location 的上下文属性。但是您可以使用名为 loc 的上下文属性,该属性使用位置类型。因此,解决方案是对其来源进行小的修改,如下所示:

const RouteComponent = React.createClass({
    childContextTypes: {
        loc: PropTypes.location
    },

    getChildContext() {
        return { location: this.props.location }
    }
});

const ChildComponent = React.createClass({
    contextTypes: {
        loc: PropTypes.location
    },
    render() {
        console.log(this.context.loc);
        return(<div>this.context.loc.query</div>);
    }
});

You could also pass down only the parts of the location object you want in your children get the same benefit. It didn't change the warning to change to the object type. Hope that helps.

您也可以只传递您希望在孩子中使用的位置对象的部分获得相同的好处。它没有更改更改为对象类型的警告。希望有帮助。

回答by Vijesh Chandera

Simple js solution:

简单的js解决方案:

queryStringParse = function(string) {
    let parsed = {}
    if(string != '') {
        string = string.substring(string.indexOf('?')+1)
        let p1 = string.split('&')
        p1.map(function(value) {
            let params = value.split('=')
            parsed[params[0]] = params[1]
        });
    }
    return parsed
}

And you can call it from anywhere using:

您可以使用以下方法从任何地方调用它:

var params = this.queryStringParse(this.props.location.search);

Hope this helps.

希望这可以帮助。

回答by Balasubramani M

You may get the following error while creating an optimized production build when using query-stringmodule.

使用查询字符串模块创建优化的生产构建时,您可能会收到以下错误。

Failed to minify the code from this file: ./node_modules/query-string/index.js:8

无法缩小此文件中的代码:./node_modules/query-string/index.js:8

To overcome this, kindly use the alternative module called stringquerywhich does the same process well without any issues while running the build.

为了克服这个问题,请使用名为stringquery的替代模块,它在运行构建时可以很好地完成相同的过程而没有任何问题。

import querySearch from "stringquery";

var query = querySearch(this.props.location.search);