Expected to return a value in arrow; function array-callback-return. Why?

后端 未结 4 1180
日久生厌
日久生厌 2021-01-07 17:59

I\'m having some issues understanding why I\'m getting a compile warning on this piece of my react code

fetch(\'/users\')
        .then(res => res.json())         


        
相关标签:
4条回答
  • 2021-01-07 18:23

    From MDN:

    The map() method creates a new array with the results of calling a provided function on every element in the calling array.

    That means the map method has to be returned. So,you should change your code like this:

    fetch('/users')
        .then(res => res.json())
        .then(data => {
            data.map(users => {
                return console.log(users);
            });
        });
    

    or use forEach() instead of map()

    0 讨论(0)
  • 2021-01-07 18:27

    Try Changing map(() => {}) to map(() => ())

    {} - Creates a code block that expects an explicit return statement.
    With () - implicit return takes place.

    0 讨论(0)
  • 2021-01-07 18:31

    If you don't need to mutate the array and just do the console.log() you can do data.forEach() instead. It shouldn't give you the warning. Map expects you to return a value after you've transformed the array.

    fetch('/users')
            .then(res => res.json())
            .then(data => {
                data.forEach(users => {
                    console.log(users);
                });
            });
    
    0 讨论(0)
  • 2021-01-07 18:43

    Your specific example is:

    data.map(users => {
       console.log(users);
    });
    

    Where data is the following array:

    [
      {id: 1, username: "Foo"},
      {id: 2, username: "Bar"},
    ]
    

    data.map function (check Array.prototype.map specification) converts one array (data in your case) to a new array. The conversion (mapping) is defined by the argument of data.map, also called the callback function. In your case, the callback function is the arrow function users => {console.log(users);}. The callback function of data.map must return a value. By returning a value for each item of the array is how data.map defines the mapping.

    But in your case the callback function does not return anything. Your intention is not to do any kind of mapping, but just to console.log. So in your case you can use data.forEach (Array.prototype.forEach) as you don't use data.map functionality.

    NOTE: Also you should have singular (rather than plural) name for the parameter of the callback function: data.map(user => {console.log(user);}); as this parameter is set to the individual element from the old array.

    0 讨论(0)
提交回复
热议问题