3 回答

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超9個(gè)贊
盡管@machineghost所說的是正確的,但事件的添加和刪除方式相同,但等式中缺少的部分是:
.bind()調(diào)用后會(huì)創(chuàng)建一個(gè)新的函數(shù)引用!
請(qǐng)參見bind()是否會(huì)更改函數(shù)引用?| 如何永久設(shè)置?
因此,要添加或刪除它,請(qǐng)將引用分配給變量:
var x = this.myListener.bind(this);
Toolbox.addListener(window, 'scroll', x);
Toolbox.removeListener(window, 'scroll', x);
這對(duì)我來說是預(yù)期的。

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超8個(gè)贊
對(duì)于那些在將React組件的偵聽器注冊(cè)到Flux存儲(chǔ)中或從Flux存儲(chǔ)中移除React偵聽器時(shí)遇到此問題的人,請(qǐng)將以下行添加到組件的構(gòu)造函數(shù)中:
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() {
// ...
}
}
添加回答
舉報(bào)