使用去抖动方法在 window 调整大小时反应设置尺寸

React set dimensions on window resize using debounce method

我正在尝试使用去抖动方法在 window 调整大小事件期间设置 window 尺寸。似乎仅在代码第一次运行时才设置尺寸。当我尝试调整 window 的大小时,尺寸不会改变。我创建了一个沙箱示例 https://codesandbox.io/s/react-example-ciq1l

您不需要在 debouncereturn 部分设置 timer

另一件事,任何时候你进入 debounce 函数,你都会被分配新的 var timer,所以 if (timer) 的检查永远不会应用

// inside contructor
this.timerRef = React.createRef(null) // for react version > 16.3

debounce(func) {
      if (this.timerRef.current) clearTimeout(this.timerRef.current);
      this.timerRef.current = setTimeout(func, 100);
  } 

编辑

因为要传param给事件监听函数(需要用到()激活),所以假设把整个函数作为回调

 window.addEventListener(
      "resize", () =>  //adding () =>
      this.debounce(() => {
        this.updateDimensions();
      })
    );

或者debounce里面可以直接引用this.updateDimensions,就不用再传func了,可以像

window.addEventListener("resize", this.debounce)

没有激活 debounce()