有什么办法可以提高 React 中这个函数的性能吗?

Is there any way I can improve the performance of this function in React?

问题

我有两个触发事件的输入,这将更新特定产品的数量(这些输入引用了产品)。

因为我可以写一个数字,比如数量,很快,通常很慢。

需要 1-2 秒(当我有更多产品时)更新产品数量...

更新产品的功能将 return 一个新的 购物篮 ,它基本上是所有产品所在的“购物车”,然后我将更新旧的和新的(有修改)。

我应该实施什么样的性能改进?

注意:我正在使用 React,该函数属于一个 Context API。

方法:修改产品数量()

export const modifyProductQuantity = (
  productToModify: ProductInterface,
  quantity: number,
  basket: ProductInterface[]
): ProductInterface[] => {
  const basketWithUpdatedProduct = basket.map((product) => {
    if (product.id === productToModify.id) {
      const totalPrice = product.pricePerMeasurement * quantity;
      const roundedTotalPrice = parseFloat(totalPrice.toFixed(2));
      const roundedTotalQuantity = parseFloat(quantity.toFixed(2));
      return {
        ...product,
        quantity: roundedTotalQuantity,
        price: roundedTotalPrice,
      };
    }
    return product;
  });
  return basketWithUpdatedProduct;
};

我可能的解决方案:

如果我在后台处理产品修改,我可能会获得更好的性能,它是这样工作的:

大家怎么看???

经过一些调试和重构后,我稍微提高了性能,但这对我来说还不够。

正如我在可能的解决方案部分中提到的那样,解决方案是使用 Hooks 实现去抖动方法(感谢 Jacob Smith)。

这里有一个很好的blog post如何创建那个钩子

对于性能优化,您可以按照以下步骤操作:

  • debouncing:你已经提到了这个性能优化技术 有关去抖动以及如何在 React 中实现这一点的更多信息,您可以查看此
  • how to implement debouncing in react
  • what is debouncing and throttling
  • useCallback hook: 你可以使用这个 hook 来记忆你的函数。以便它可以保留一些结果以供将来参考。你可以阅读更多相关内容
  • more about useCallback
  • 使用适当的数据结构:我们知道在对象数组中找到一个 id 需要 O(n) 次。我们可以将该数组转换为地图,以便在 O(1) 时间内我们可以识别要更新的对象,地图本质上是迭代的,因此它将在您的情况下解决数组的目的。
  • 注意:数据结构和体系结构在优化中比钩子和去抖动等花哨的技术起着重要作用