3 回答

TA贡献1784条经验 获得超9个赞
尽管@machineghost所说的是正确的,但事件的添加和删除方式相同,但等式中缺少的部分是:
.bind()调用后会创建一个新的函数引用!
请参见bind()是否会更改函数引用?| 如何永久设置?
因此,要添加或删除它,请将引用分配给变量:
var x = this.myListener.bind(this);
Toolbox.addListener(window, 'scroll', x);
Toolbox.removeListener(window, 'scroll', x);
这对我来说是预期的。

TA贡献1804条经验 获得超8个赞
对于那些在将React组件的侦听器注册到Flux存储中或从Flux存储中移除React侦听器时遇到此问题的人,请将以下行添加到组件的构造函数中:
class App extends React.Component {
constructor(props){
super(props);
// it's a trick! needed in order to overcome the remove event listener
this.onChange = this.onChange.bind(this);
}
// then as regular...
componentDidMount (){
AppStore.addChangeListener(this.onChange);
}
componentWillUnmount (){
AppStore.removeChangeListener(this.onChange);
}
onChange () {
let state = AppStore.getState();
this.setState(state);
}
render() {
// ...
}
}
添加回答
举报