避免在React中使用"no-unused-vars"循环错误 [英] Avoid React "no-unused-vars" error with loop

查看:296
本文介绍了避免在React中使用"no-unused-vars"循环错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在根据另一个数组中的项目数量生成一个对象数组.非常简单,我正在执行以下操作,效果很好.

I am generating an array of objects based on the quantity of items in another array. Pretty simple, I'm just doing the following, which works fine.

for(let i in myArray){
  newArray.push({
    var1: someFunctionValue(),
    var2: anotherFunctionValue()
  });
}

但是,由于未使用"i",React(ESLint?)给我警告"i"已分配一个值,但从未使用过-无未使用的变量.

However, because "i" is not being used, React (ESLint?) gives me the warning 'i' is assigned a value but never used - no-unused-vars.

我应该有更好的方法吗?我真的看不到一种在不产生此错误的情况下实现我想要的方法的方法.

Is there a better way I should be doing this? I don't really see a way to achieve what I want without producing this error.

推荐答案

您正在对数组使用for-in循环,而不使用可枚举的键(索引).您应该改用Array#forEach,并且由于它接受回调,因此您可以省略任何参数:

You're using a for-in loop over an array, without using the enumerable keys (indices). You should use Array#forEach instead, and since it accepts a callback, you can just omit any arguments:

myArray.forEach(() => { // No callback args
  newArray.push({
    var1: someFunctionValue(),
    var2: anotherFunctionValue()
  });
});

此外,既然我正在读取您的变量名,似乎您正在尝试执行映射操作,例如对于myArray中的每个元素,您都希望newArray中的一个新元素与每个索引相关联.如果是这样,更好的方法是Array#map您的myArray:

Also, now that I'm reading your variable names, it seems you're trying to do a mapping operation, as in for every element in myArray, you want a new one in newArray associated with each index. If that's the case, the better method is to Array#map your myArray:

const newArray = myArray.map(() => ({
  var1: someFunctionValue(),
  var2: anotherFunctionValue(),
}));

不需要任何中介,而且简洁明了.

There's no need for any intermediacy and it's concise.

这篇关于避免在React中使用"no-unused-vars"循环错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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