我有一个事件处理程序,需要访问React组件(this)才能使用this.setState()
。删除组件后,我希望事件处理程序被垃圾回收。
我问自己是否有比现有设置更好的方法:
class MyComponent extends React.Component {
constructor(props) {
super(props);
// Preserve this context
this.handleKeyDown = this.handleKeyDown.bind(this);
}
render() {
return <div></div>;
}
handleKeyDown() {
// this.setState(...);
}
componentWillMount() {
window.addEventListener("keydown", this.handleKeyDown);
}
componentWillUnmount() {
// Clean up
window.removeEventListener("keydown", this.handleKeyDown);
}
};
修改
特别是这条线对我来说似乎有些苛刻:
// Preserve this context
this.handleKeyDown = this.handleKeyDown.bind(this);
答案 0 :(得分:0)
经过一番讨论(见问题评论)后,人们一致认为这种方式完全没问题:
enter code here
connection.query('SELECT * FROM departments WHERE manager_id > :id', [110], {
splitResults: true, //True to enable to split the results into bulks, each bulk will invoke the provided callback (last callback invocation will have empty results)
bulkRowsAmount: 100 //The amount of rows to fetch (for splitting results, that is the max rows that the callback will get for each callback invocation)
}, function onResults(error, results) {
if (error) {
//handle error...
} else if (results.length) {
//handle next bulk of results
} else {
//all rows read
}
});