反应。实现 setState 方法的去抖函数

React. Debouncing function that implements setState method

我正在开发一个简单的临时组件,将视口尺寸传递给它的子组件。在 window 调整大小时,我启动 handleResize 方法以将新的 window 尺寸传递给子组件。我想使用 lodash 中的 debounce func 来最小化调用 handleResize 方法的次数 (ref).

import React from 'react'

import debounce from 'lodash/debounce'

const getDimensions = (Component) => {
  return class GetDimensions extends React.Component {
    constructor () {
      super()

      this.state = {
        viewport: {
          x: window.innerWidth,
          y: window.innerHeight
        }
      }
    }

    handleResize = () => {
      this.setState(() => ({viewport: {x: window.innerWidth, y: window.innerHeight}}))
    }

    componentDidMount = () => {
      if (window) window.addEventListener('resize', debounce(this.handleResize, 400))
    }

    componentWillUnmount = () => {
      if (window) window.removeEventListener('resize', this.handleResize)
    }

    render () {
      return (
        <Component
          {...this.props}
          viewport={this.state.viewport}
        />
      )
    }
  }
}

export default getDimensions

它按预期工作,但我不断收到警告:

有人知道这是怎么回事吗?

请告诉我

请记住,您并没有删除该活动。 if (window) window.addEventListener('resize', debounce(this.handleResize, 400)) 将改变函数和 return 包装函数,删除事件只是传递原始的 this.handleResize,不会被发现。

您需要在构造函数中 this.handleResize = debounce(this.handleResize, 400)

tl;dr:组件将卸载但事件将继续触发。