简体   繁体   English

对array.map的ESLint prefer-arrow-callback

[英]ESLint prefer-arrow-callback on array.map

import React from 'react';

export default class UIColours extends React.Component {
  displayName = 'UIColours'

  render() {
    const colours = ['black', 'red', 'white', 'orange', 'green', 'yellow', 'blue', 'darkblue', 'lilac', 'purple', 'darkPurple'];
    return (
      <div className="ui-colours-container row bg-white">
        <div className="col-md-16 col-xs-16 light">
          <div className="color-swatches">
            {colours.map(function(colour, key) {
              return (
                <div key={key} className={'strong color-swatch bg-' + colour}>
                  <p>{colour}</p>
                </div>
              );
            })}
          </div>
        </div>
      </div>
   );
  }
}

12:26 error Unexpected function expression prefer-arrow-callback 12:26错误意外的函数表达式prefer-arrow-callback

I've looked at the map documentation and can't find a good example of multiple parameters. 我查看了地图文档,找不到多个参数的好例子。

That ESLint rule occurs because you have an anonymous function as a callback, so it's suggesting that you use an arrow function instead. 因为你有一个匿名函数作为回调,所以发生了ESLint规则,所以它建议你使用箭头函数。 To use multiple parameters with arrow functions you need to wrap the parameters with parentheses, eg: 要在箭头函数中使用多个参数,您需要用括号包装参数,例如:

someArray.map(function(value, index) {
  // do something
});

someArray.map((value, index) => {
  // do something
});

As always, the MDN docs for arrow functions has a very detailed explanation of the variations that can be used with arrow functions. 与往常一样, 箭头函数的MDN文档对箭头函数可以使用的变体进行了非常详细的说明。

Alternatively, you could just disable that ESLint rule or change it so that it won't warn about named callbacks. 或者,您可以禁用该ESLint规则或更改它,以便它不会警告命名回调。 The documentation for that ESLint rule is prefer-arrow-callback . 该ESLint规则的文档是prefer-arrow-callback

You could rewrite the map like this: 您可以像这样重写map

{colours.map(colour => (
  <div key={`colour-${colour}`} className={`strong color-swatch bg-${colour}`}>
    <p>{colour}</p>
  </div>
)}

Given colour names seem to be unique, you could use them as key s without a problem. 鉴于颜色名称似乎是唯一的,您可以使用它们作为key而没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM