预计会返回箭头值; function array-callback-return。为什么? [英] Expected to return a value in arrow; function array-callback-return. Why?

查看:156
本文介绍了预计会返回箭头值; function array-callback-return。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一些问题,理解为什么我在这段反应代码上收到编译警告

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

我得到的警告是预计会在箭头函数中返回一个值array-callback-return

但是我仍然从我的 / users ,它们分别打印到控制台。对象是:

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"
    }

我错过了一个返回语句,或者我错过了 map 如何在之后返回值.then()?我不清楚为什么会出现编译警告。

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.

推荐答案

data.map function(检查 Array.map 规范: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map )转换一个数组(在您的情况下,数据)到新数组。此映射由 data.map 的参数定义。 data.map 的参数(回调函数),在你的情况下是箭头函数 users => {console.log(users);} ,必须返回一个值。通过为每个数组元素返回一个值, data.map 定义了映射。

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.

但在你的情况下,回调函数不会返回任何内容,只需 console.log s。在您的情况下,您可以使用 data.forEach https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach )因为你不使用 Array.map 功能。

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.

注意:如果您决定使用 data.map 你应该有一个单数(而不是复数)名称作为回调的参数: data.map(user => {console.log(user);}); 现在为每个用户调用。

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.

这篇关于预计会返回箭头值; function array-callback-return。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆