Array减少逗号操作符的意外使用



我得到一个"意外使用逗号操作符no-sequences"警告-在。reduce -但我不确定如何解决这个问题。

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

引用的代码使用(有人会说ab使用)逗号操作符,以避免使用箭头函数的函数体形式。删除逗号操作符的最小更改是将{}放在函数体周围,并执行显式return:

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

作为风格的问题,虽然,我建议不要在那里使用reduce。(我有相当多的公司不喜欢reduce以外的函数式编程预定义,可重用的reducer。)

在这段代码中,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 getQueryParams = () => Object.fromEntries(
    new URLSearchParams(this.props.location.search)
    .entries()
);

生活的例子:

const search = "?bar=Testing%201%202%203&baz=2";
console.log(
    Object.fromEntries(
        new URLSearchParams(search)
        .entries()
    )
);

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

.reduce((r,e) => {
     r[e.split('=')[0]] = decodeURIComponent(e.split('=')[1]);
     return r;
}, {});

另一种方法是使用Object.assign:

let search = ["item=test","name=code%28","foo=%20bar"]
let result = search.reduce((r,e) => 
Object.assign(r,{[e.split('=')[0]] : decodeURIComponent(e.split('=')[1])}), {});
console.log(result)

最新更新