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

Pet*_*son 34 reactjs react-router react-router-dom

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

react-router-dom@4.0.0 props.location只有props.location.search一个字符串就像?foo=bar&other=thing.

也许我需要手动解析和解构该字符串以找到foo或的值other.

屏幕截图console.log(this.props): 在此输入图像描述 (注意从?artist=band这里我想得到的值是从artist哪个值band)

Tyl*_*nis 79

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

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

const parsed = queryString.parse(props.location.search);
Run Code Online (Sandbox Code Playgroud)

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

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

您可以在此处详细了解该决定

  • URLSearchParams在iOS和SSR上不可用.query-string是更稳定的解决方案. (4认同)
  • 你在哪里添加这个,所以它可以在每个路线的渲染? (3认同)
  • 如果你需要支持 IE11,这个包目前有问题。 (2认同)

Bal*_*i M 18

使用query-string模块创建优化的生成构建时,可能会出现以下错误.

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

为了克服这个问题,请使用名为stringquery的替代模块,它可以在运行构建时完成相同的过程而不会出现任何问题.

import querySearch from "stringquery";

var query = querySearch(this.props.location.search);
Run Code Online (Sandbox Code Playgroud)

谢谢.

  • 为了解决这个问题,您还可以使用旧版本的 `query-string`。您可以通过执行 `yarn add query-string@5` 或 `npm install query-string@5` 来安装它 (2认同)

Ame*_*icA 12

我提供了一些小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;
                }, {}
            )
        : {}
};
Run Code Online (Sandbox Code Playgroud)

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


mid*_*mer 7

使用第三方包对于一个简单的问题来说是过度的:

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});
}
Run Code Online (Sandbox Code Playgroud)

这将简单地将 URL 查询参数转换为对象。


DOR*_*ITO 5

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

对于那些使用查询字符串的人,您可能必须做类似的事情

var nameYouWant = queryString.parse(this.props.location.search).nameYouWant;
Run Code Online (Sandbox Code Playgroud)

以我为例,这会发生,并且this.props.location.search.theUrlYouWant会拒绝工作。泰勒提到的第二个选项也通过一些类似的调整对我有用。