不要在循环中创建函数no-loop-func -React JS

时间:2019-01-09 07:00:21

标签: javascript node.js reactjs

我正在尝试使用lodash locationbar查找数组的索引。但是我的反应控制台显示了一些警告。可以解决吗?

let wishListData = wishList.result;
                let j = 0; const jMax = wishListData.length;
                for (; j < jMax; j++) {

                    var index = _.findIndex(products.result, function (product) {
                        return product.id === wishListData[j]['pid']
                    });

                    if (index !== -1) {
                        products.result[index]['isWishList'] = true;
                    }
                }

2 个答案:

答案 0 :(得分:1)

使用wishList.result而不是forEach循环遍历for,您将避免该警告:

wishListData.forEach(({ pid }) => {
  const index = _.findIndex(products.result, ({ id }) => id === pid);
  if (index !== -1) {
    products.result[index].isWishList = true;
  }
});

请注意,这是 linter警告,而不是Javascript错误。您的代码有效,linter只是认为它令人困惑-最好在可能的情况下使用数组方法而不是循环。

此外,如果需要,可以随时删除_库,而仅使用内置的Javascript方法:

wishListData.forEach(({ pid }) => {
  const product = products.result.find(({ id }) => id === pid);
  if (product) {
    product.isWishList = true;
  }
});

或者,对于O(N)解决方案而不是O(N^2)解决方案,请先找出所有pid,然后遍历产品:

const pids = new Set(wishListData.map(({ pid }) => pid));
products.result.forEach((product) => {
  if (pids.has(product.id)) {
    product.isWishList = true;
  }
});

答案 1 :(得分:0)

您也可以尝试以下操作:

  • 您应该创建新的对象以最大程度地减少副作用,而不是在product中更改products.result[index]['isWishList'] = true;
  • 此外,您可以创建PID列表并仅检查索引,而不是在wishListData上循环。如果此列表是在外部创建的,则也可以在外部创建PID的列表。这样可以减少每次处理的时间
const wishListPID = wishList.result.map((x) => x.pid);
const result = products.result.map((product) => {
  const isWishList = wishListPID.indexOf(product.id) !== -1;
  return { ...product, isWishList }
});