我有一个项目列表。每个项目都可以通过传递itemId
显示在MyComponent
中。要聆听所选项目的更改,我正在通过myService
:
<MyComponent myService={myService} id={itemId}/>
组件获取项目详细信息并开始收听服务:
componentDidMount() {
this.fetchItemDetails(this.props.id); // fetch the item details
this.props.myService.listensTo('eventId', () => {
// something changed, fetch again ...
});
}
componentWillUnmount() {
// reset / unregister the listener for this instance
}
问题:每次安装MyComponent
时都会注册侦听器,这成为多个实例的问题。
我只想听一个主动的,安装的组件,并在卸载后立即不遵守。
有什么想法?
预先感谢!
您必须对使用作为回调的函数进行引用。通常,侦听器要做的是保留所有回调函数的内部结构排除在列表之外。由于唯一给您的信息是对回调函数本身的引用。我会做以下操作:
constructor(){
super();
this.myListener = this.myListener.bind(this); // Do this only if necessary
}
componentDidMount() {
this.fetchItemDetails(this.props.id); // fetch the item details
this.props.myService.listensTo('eventId', myListener);
}
myListener(){
//...
}
componentWillUnmount() {
// reset / unregister the listener for this instance
this.props.myService.deregister('eventId', myListener);
}
重要的是要保持对功能的引用,这就是为什么将绑定放入构造函数很重要的原因。