如何在react-router v4中解析查询字符串

时间:2017-03-17 16:07:20

标签: reactjs react-router react-router-dom

在react-router v3中,我可以使用props.location.query.foo访问它(如果当前位置为?foo=bar

react-router-dom@4.0.0 props.locationprops.location.search只有?foo=bar&other=thing字符串。

也许我需要手动解析和解构该字符串以找到fooother的值。

console.log(this.props)的屏幕截图: enter image description here (请注意,?artist=band来自artist我希望从band得到值Task

7 个答案:

答案 0 :(得分:67)

看起来你已经假设正确了。解析查询字符串的能力是从V4中取出的,因为多年来一直有人要求支持不同的实现。有了这个,团队决定最好让用户决定实现的样子。我们建议导入查询字符串lib。到目前为止,one you mentioned对我来说非常有用。

const queryString = require('query-string');

const parsed = queryString.parse(props.location.search);

如果您想要原生的东西并且它可以满足您的需求,您也可以使用new URLSearchParams

const search = props.location.search; // could be '?foo=bar'
const params = new URLSearchParams(search);
const foo = params.get('foo'); // bar

您可以阅读有关决定here

的更多信息

答案 1 :(得分:17)

使用query-string模块时,在创建优化的生产版本时可能会出现以下错误。

  

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

为了克服这个问题,请使用名为stringquery的替代模块,该模块在运行构建时可以很好地执行相同的过程。

import querySearch from "stringquery";

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

谢谢。

答案 2 :(得分:4)

很高兴我找到了这篇文章。感谢您的链接,几个小时后我终于升级了我的代码。

对于使用query-string的人,您可能需要执行类似

的操作
var nameYouWant = queryString.parse(this.props.location.search).nameYouWant;

这种情况发生在我的案例中,this.props.location.search.theUrlYouWant拒绝合作。 Tyler提到的第二个选项也为我做了一些类似的调整。

答案 3 :(得分:2)

我提供了ES6的小形状功能,超棒,重量轻且实用:

getQueryStringParams = query => {
    return query
        ? (/^[?#]/.test(query) ? query.slice(1) : query)
            .split('&')
            .reduce((params, param) => {
                    let [key, value] = param.split('=');
                    params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
                    return params;
                }, {}
            )
        : {}
};

每件事都在这里,希望对您有所帮助。

答案 4 :(得分:2)

使用第三方软件包对于简单的解决方案来说是过大的事情

componentDidMount() {
        const query = new URLSearchParams(
            this.props.location.search
        );

        let data= {};

        for (let params of query.entries()) {
            data[params[0]] = +params[1];
        }
        this.setState({ urldata: data});
    }

这只会将URL数据转换为对象。

答案 5 :(得分:2)

您可以使用简单的函数来提取查询参数,而不是安装软件包。

//Param Extractor
const parseParams = (params = "") => {
  const rawParams = params.replace("?", "").split("&");
  const extractedParams = {};
  rawParams.forEach((item) => {
    item = item.split("=");
    extractedParams[item[0]] = item[1];
  });
  return extractedParams;
};

//Usage
const params = parseParams(this.props?.location?.search); // returns an object like:
// {id:1,name:john...}

答案 6 :(得分:0)

我很惊讶没有人提到UrlSearchParam.get方法。