javascript - 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
解决方案
在构造函数中绑定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
})
}
}
推荐阅读
- python - 插入并返回 :array
- python - 将 `subprocess.run` 与包含空格的参数一起使用
- python - 无法在 Spyder/Anaconda 中安装 pandasql
- google-chrome - 无头 Chrome 命令行 - 设置超时
- ruby-on-rails - 为什么,在使用 Faker Gem 时会出现此错误?从以前的答案中,我了解到这与我的 database.yml 有关
- office-js - 如何在office js中添加多个选定的单元格注释?
- window-functions - 分区之间的 clickhouse 移动平均线
- r - 如何在R中的列中打乱值?
- go - Dependabot 用于更新跟踪提交的 go 依赖项
- php - pdo 执行语句中的方括号有什么作用?