React组件监听窗口变化
基本思路:
改变事件方法中的this指向
constructor(props) {
this.resizeBind = this.resizeTTY.bind(this)
}
添加监听
componentDidMount() {
window.addEventListener('resize', this.resizeBind)
}
注销事件
componentWillUnmount() {
window.removeEventListener('resize', this.resizeBind)
}
错误写法:
- 不在constructor中绑定resizeTTY的this指向,这时resizeTTY中的this指向window而不是React组件,在resizeTTY中获取React组件的state或者使用setState方法会抛出错误:(socketList是state的属性)
Cannot read property 'socketList' of undefined
- 尝试在constructor中用bind绑定this但不赋值给新函数,这时编译不再报错,但窗口变化时resizeTTY执行仍然抛出错误,这时输出this仍指向window对象
这是因为bind()函数执行后会返回指定this改造后的原函数拷贝,但原函数不会改变,所以我们需要使用的是bind返回的新函数而不是resizeTTY
constructor(props) {
this.resizeTTY.bind(this)
}
componentDidMount() {
window.addEventListener('resize', this.resizeTTY)
}
componentWillUnmount() {
window.removeEventListener('resize', this.resizeTTY)
}
Cannot read property 'socketList' of undefined
- 不在componentWillUnmount生命周期中注销事件,会导致组件销毁后仍在监听