Javascript 数组减少逗号运算符no序列的意外使用

Javascript 数组减少逗号运算符no序列的意外使用,javascript,Javascript,我在.reduce上收到“意外使用逗号运算符无序列”警告,但我不确定如何解决此问题 const getQueryParams = () => this.props.location.search .replace('?', '') .split('&') .reduce((r,e) => (r[e.split('=')[0]] = decodeURIComponent(e.split('=')[1]), r), {}); 您可以重写reduce

我在.reduce上收到“意外使用逗号运算符无序列”警告,但我不确定如何解决此问题

const getQueryParams = () => 
  this.props.location.search
    .replace('?', '')
    .split('&')
    .reduce((r,e) => (r[e.split('=')[0]] = decodeURIComponent(e.split('=')[1]), r), {});

您可以重写
reduce
调用,以避免赋值表达式(和逗号运算符),将箭头函数表达式语法转换为块语法(请参阅):

引用的代码使用(有些人会说滥用)逗号运算符,以避免使用arrow函数的函数体形式。删除逗号运算符的最小更改是在函数体周围放置
{}
,并执行显式
返回操作

const getQueryParams = () => 
    this.props.location.search
        .replace('?', '')
        .split('&')
        .reduce((r,e) => {
            r[e.split('=')[0]] = decodeURIComponent(e.split('=')[1]);
            return r;
        }, {});

不过,就风格而言,我建议根本不要使用
reduce
。(我有点不喜欢使用预定义的、可重用的缩减器进行函数式编程之外的
reduce
。)

在该代码中,
reduce
只是一个循环;累加器从不改变,它总是同一个对象。所以我只需要使用一个循环:

const getQueryParams = () => {
    const result = {};
    for (const e of this.props.location.search.replace("?", "").split("&")) {
        result[e.split("=")[0]] = decodeURIComponent(e.split("=")[1]);
    }
    return result;
};
我可能还会删除对
split
的冗余调用:

const getQueryParams = () => {
    const result = {};
    for (const e of this.props.location.search.replace("?", "").split("&")) {
        const [key, value] = e.split("=");
        result[key] = decodeURIComponent(value);
    }
    return result;
};
最后,查询字符串中的键和值都是URI编码的,因此
decodeURIComponent
应同时用于:

const getQueryParams = () => {
    const result = {};
    for (const e of this.props.location.search.replace("?", "").split("&")) {
        const [key, value] = e.split("=");
        result[decodeURIComponent(key)] = decodeURIComponent(value);
    }
    return result;
};
如果这些键只是字母数字之类的,它就可以不用了,但它是不正确的


但是,从语法上退一步,您不需要发明自己的函数来解析查询字符串参数。浏览器:

实例:

const search=“?bar=Testing%201%202%203&baz=2”;
console.log(
Object.fromEntries(
新的URLSearchParams(搜索)
.条目()
)

);另一种方法是使用
对象。分配

let search=[“item=test”,“name=code%28”,“foo=%20bar”]
让result=search.reduce((r,e)=>
赋值(r,{[e.split('=')[0]]:decodeURIComponent(e.split('=')[1]),{});

console.log(result)
of?如果将
reduce
替换为
map
,是否会得到完全不同的ESLint警告?警告是关于函数的内容,而不是函数的名称。它很重要-因为它不是一个映射-它是一个reduce-所以在提出问题时主题不匹配。因此,它不是完全相同的场景的副本,即使它是关于内容的。顺便说一句,它看起来像是在试图解析URL参数。只需使用
this.props.location.searchParams
,或
新URL(this.props.location).searchParams
,具体取决于
this.props.location
是否为
URL
。您可以在其上调用
.entries()
,并将其包装在
对象中。fromEntries(
可获得普通对象。看见
const getQueryParams = () => {
    const result = {};
    for (const e of this.props.location.search.replace("?", "").split("&")) {
        const [key, value] = e.split("=");
        result[decodeURIComponent(key)] = decodeURIComponent(value);
    }
    return result;
};
const getQueryParams = () => Object.fromEntries(
    new URLSearchParams(this.props.location.search)
    .entries()
);