首页 > 解决方案 > debounce and react window resize this reference issue

问题描述

我正在使用react和lodash的debounce方法。我遇到的问题是当用户调整窗口大小时更新状态。

我遇到的问题是,当用户在此函数中调整窗口大小时,this它指的是与组件相反的组件:window

window.addEventListener('resize', this.delayedCallback)

我尝试过设置const that = this等,但无法获得正确的范围。有谁知道如何解决这个问题?

请参见下面的代码:

class Card extends Component {

  constructor(props) {
    super(props)
    this.state = {
      cardElWidth: null
    }
    this.delayedCallback = debounce(this.setCardWidth, 1000);
    this.CardEl = React.createRef()
  }

  componentDidMount () {
    this.setCardWidth()
    window.addEventListener('resize', this.delayedCallback)
  }

  setPlayerCardWidth() {
    this.setState({
      cardElWidth: this.CardEl.current.offsetWidth
    })
  } ... rest of code

标签: javascriptreactjsecmascript-6thislodash

解决方案


在构造函数中绑定setCardWidth方法:this

constructor(props) {
  super(props)
  this.state = {
    cardElWidth: null
  }
  this.setCardWidth = this.setCardWidth.bind(this)
  this.delayedCallback = debounce(this.setCardWidth, 1000)
  this.CardEl = React.createRef()
}

或者通过直接在 debounce 表达式中绑定来缩短:

constructor(props) {
  super(props)
  this.state = {
    cardElWidth: null
  }
  this.delayedCallback = debounce(this.setCardWidth.bind(this), 1000)
  this.CardEl = React.createRef()
}

setCardWidth您可以将 转换为类属性,并使用箭头函数自动绑定到 ,而不是在构造函数中使用 bind this

注意:这需要 babel 的plugin-proposal-class-properties

setPlayerCardWidth = () => {
  this.setState({
    cardElWidth: this.CardEl.current.offsetWidth
  })
}

如果你使用类属性,你也可以删除构造函数:

class Card extends Component {
  state = {
    cardElWidth: null
  }

  CardEl = React.createRef()

  componentDidMount() {
    this.setCardWidth()
    window.addEventListener('resize', this.delayedCallback)
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.delayedCallback)
  }

  delayedCallback = debounce(this.setCardWidth, 1000)

  setPlayerCardWidth = () => {
    this.setState({
      cardElWidth: this.CardEl.current.offsetWidth
    })
  }
}

推荐阅读