【问题标题】:Arrow function expected a return value箭头函数期望返回值
【发布时间】:2020-08-20 16:29:51
【问题描述】:

如何解决此警告?我使用 .map 的方式有问题吗?

我正在尝试显示通过包含该信息的另一个数组接收到的每个月的总销售额和总收入,以便稍后在图表上显示。

var arrEneSales = [0, 0, 0, 0, 0, 0];
var arrJulSales = [0, 0, 0, 0, 0, 0];

var arrMoneyEne = [0, 0, 0, 0, 0, 0];
var arrMoneyJul = [0, 0, 0, 0, 0, 0];

this.state.sales.map((item) => {
  var date = new Date(item[0].q1_date.seconds * 1000);
  if (date.getMonth() + 1 < 6) {
    arrEneSales[date.getMonth() + 1] += 1;
    arrMoneyEne[date.getMonth() + 1] += item[0].total;
  } else {
    arrJulSales[date.getMonth() + 1] += 1;
    arrMoneyJul[date.getMonth() + 1] += item[0].total;
  }
});

【问题讨论】:

  • 如果你不需要返回值那么你可以使用.forEach而不是.map

标签: javascript arrays reactjs


【解决方案1】:

Map 用于返回数组。如果您不想返回任何内容,只需遍历数组,请不要使用 map 像这样使用 forEach

this.state.sales.forEach((item) => {
  var date = new Date(item[0].q1_date.seconds * 1000);
  if (date.getMonth() + 1 < 6) {
    arrEneSales[date.getMonth() + 1] += 1;
    arrMoneyEne[date.getMonth() + 1] += item[0].total;
  } else {
    arrJulSales[date.getMonth() + 1] += 1;
    arrMoneyJul[date.getMonth() + 1] += item[0].total;
  }
});

地图工作是这样的。

var returnedArray = this.state.sales.map((item) => {
  var date = new Date(item[0].q1_date.seconds * 1000);
  if (date.getMonth() + 1 < 6) {
    arrEneSales[date.getMonth() + 1] += 1;
    arrMoneyEne[date.getMonth() + 1] += item[0].total;
  } else {
    arrJulSales[date.getMonth() + 1] += 1;
    arrMoneyJul[date.getMonth() + 1] += item[0].total;
  }
  return item;
});

【讨论】:

    【解决方案2】:

    从类型定义

    /**
     * Performs the specified action for each element in an array.
     * @param callbackfn  A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
     * @param thisArg  An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
     */
    forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
    
    /**
     * Calls a defined callback function on each element of an array, and returns an array that contains the results.
     * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
     * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
     */
    map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
    

    所以你看到map 函数应该返回一个数组。 你应该使用forEach,它什么都不返回/void

    访问 MDN 获取有关地图功能的 javascript 文档

    【讨论】:

      猜你喜欢
      • 2017-12-04
      • 2020-05-06
      • 2021-11-09
      • 2022-01-20
      • 2021-01-15
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      • 2022-11-17
      相关资源
      最近更新 更多