Warning Unexpected unnamed function func-names under, ESLint rule

喜欢而已 提交于 2021-02-04 22:13:30

问题


My eslint version is 4.18.2, it would give a warning like this:

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))), []);

回答1:


These are two different issues…

Unexpected unnamed function

This is, as pointed out by Constantin, the ESLint rule 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:

!hash[curr.farmerId] && (hash[curr.farmerId] = prev.push(curr));

You can rewrite it as an if statement:

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:

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.




回答2:


If we need to export without declaring, it can be used as below

export default () => {

// your code goes here

}


来源:https://stackoverflow.com/questions/52735032/warning-unexpected-unnamed-function-func-names-under-eslint-rule

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!