[英]Warning Unexpected unnamed function func-names under, ESLint rule
My eslint
version is 4.18.2, it would give a warning like this:我的
eslint
版本是 4.18.2,它会给出这样的警告:
Unexpected unnamed function
意外的未命名函数
Expected an assignment or function call and instead saw an expression期望赋值或函数调用,而是看到了一个表达式
When defining functions in such a way:以这种方式定义函数时:
const farmerIds = a.reduce((function (hash) {
return function (prev, curr) {
!hash[curr.farmerId] && (hash[curr.farmerId] = prev.push(curr));
return prev;
};
}(Object.create(null))), []);
These are two different issues…这是两个不同的问题……
Unexpected unnamed function意外的未命名函数
This is, as pointed out by Constantin, the ESLint rule func-names .正如康斯坦丁所指出的,这就是 ESLint 规则func-names 。
If you don't want to disable this rule, you can either use names for your functions, like so:如果您不想禁用此规则,您可以为您的函数使用名称,如下所示:
const farmerIds = a.reduce((function reducer(hash) {
return function fn(prev, curr) {
!hash[curr.farmerId] && (hash[curr.farmerId] = prev.push(curr));
return prev;
};
}(Object.create(null))), []);
Or, and this I would recommend personally, use arrow functions:或者,我个人建议使用箭头函数:
const farmerIds = a.reduce(
(hash => {
return (prev, curr) => {
!hash[curr.farmerId] && (hash[curr.farmerId] = prev.push(curr));
return prev;
};
})(Object.create(null)),
[]
);
Expected an assignment or function call and instead saw an expression期望赋值或函数调用,而是看到了一个表达式
ESLint is complaining about this line, which is indeed an expression, not an assignment or function call: ESLint 抱怨这一行,它确实是一个表达式,而不是赋值或函数调用:
!hash[curr.farmerId] && (hash[curr.farmerId] = prev.push(curr));
You can rewrite it as an if
statement:您可以将其重写为
if
语句:
if (!hash[curr.farmerId]) {
hash[curr.farmerId] = prev.push(curr);
}
Fixing both修复两者
Putting the code examples above together, this code should run without ESLint complaining:将上面的代码示例放在一起,这段代码应该可以在没有 ESLint 抱怨的情况下运行:
const farmerIds = a.reduce(
(hash => (prev, curr) => {
if (!hash[curr.farmerId]) {
hash[curr.farmerId] = prev.push(curr);
}
return prev;
})(Object.create(null)),
[]
);
Note that I've also removed the curly braces around the body of the first arrow function, which is a nice additional feature of arrows to keep the code more concise.请注意,我还删除了第一个箭头函数主体周围的花括号,这是箭头的一个很好的附加功能,可以使代码更加简洁。
If we need to export without declaring, it can be used as below如果我们需要在不声明的情况下导出,可以如下使用
export default () => {
// your code goes here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.