Expected to return a value in arrow; function arra

2019-02-25 05:54发布

问题:

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())
        .then(data => {
            data.map(users => {
                console.log(users);
            });
        });

The warning I'm getting is Expected to return a value in arrow function array-callback-return

However I'm still get the json object values from my /users, and they are printed to the console individually. The object is:

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

Am I missing a return statement, or am I missing something with how map returns values after a .then()? I'm unclear on why the compile warning would appear at all.

回答1:

data.map function (check Array.map specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) converts one array (data in your case) to a new array. This mapping is defined by the argument of data.map. The argument of data.map (the callback function), in your case the arrow function users => {console.log(users);}, must return a value. By returning a value for each array element is how data.map defines the mapping.

But in your case the callback function does not return anything, just console.logs. In your case you can use data.forEach (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) as you don't use Array.map functionality.

NOTE: If you decide to use data.map you should have a singular (rather than plural) name as the argument of callback: data.map(user => {console.log(user);}); which is now called for each user.



回答2:

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()



回答3:

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);
            });
        });