import throttle from 'lodash/throttle';

// 创建节流函数,只需创建一次
const throttledCalculatePrice = throttle((goodsList, couponList) => {
    calculatePrice(goodsList, couponList);
}, 200);

<Stepper defaultValue={item.number} min={1} onChange={(val) => {
    item.number = val;
    setLoadingType(true);
    // 调用节流函数
    throttledCalculatePrice(goodsList, couponList);
}} />
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

一开始以为是函数问题后来发现是因为节流函数在每次渲染时都被重新创建了。

将节流函数定义移到组件外部或 useMemo 内部:确保节流函数在组件的整个生命周期中保持不变。

import React, { useMemo } from 'react';
import throttle from 'lodash/throttle';

const MyComponent = ({ item, goodsList, couponList, setLoadingType }) => {
  // 使用 useMemo 保证节流函数只创建一次
  const throttledCalculatePrice = useMemo(
    () => throttle((goodsList, couponList) => {
      calculatePrice(goodsList, couponList);
    }, 200),
    [] // 空依赖数组确保节流函数只创建一次
  );

  return (
    <Stepper
      defaultValue={item.number}
      min={1}
      onChange={(val) => {
        item.number = val;
        setLoadingType(true);
        // 调用节流函数
        throttledCalculatePrice(goodsList, couponList);
      }}
    />
  );
};

export default MyComponent;
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.