【问题标题】:React. Debouncing function that implements setState method做出反应。实现 setState 方法的去抖函数
【发布时间】:2017-08-07 11:03:46
【问题描述】:

我正在开发一个简单的 hoc 组件,它将视口尺寸传递给它的子组件。在调整窗口大小时,我启动 handleResize 方法将新的窗口尺寸传递给子组件。我想使用 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

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

有人知道怎么回事吗?

请告诉我

【问题讨论】:

    标签: reactjs higher-order-components debounce


    【解决方案1】:

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

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

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

    【讨论】:

    • Dimitar Christoff,感谢您的回答和解释!有效!
    猜你喜欢
    • 2016-12-23
    • 2021-05-08
    • 2016-03-08
    • 2019-03-20
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    相关资源
    最近更新 更多