简体   繁体   中英

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

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. 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.

Alternatively, you could just disable that ESLint rule or change it so that it won't warn about named callbacks. The documentation for that ESLint rule is prefer-arrow-callback .

You could rewrite the map like this:

{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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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