【发布时间】:2019-05-20 19:51:30
【问题描述】:
我需要在 firebase 实时数据库上监听一个会经常更新的引用,所以我尝试将监听器封装在一个组件中,如果用户无法查看组件,监听器将是关闭。
我创建了一个高阶组件以避免泄漏侦听器,如下所示:
const FirebaseListener = (WrappedComponent) => {
return class extends Component {
state = {
ref: null,
data: {},
}
componentDidMount() {
const { device } = this.props;
const ref = repository.listenDevice(device.id);
ref.once('value').then((snapshot) => {
const data = snapshot.val();
this.setState({ data });
});
ref.on('child_changed', (snapshot) => {
const value = snapshot.val();
const prop = snapshot.key;
const { data } = this.state;
this.setState({ data: { ...data, [prop]: value } });
});
this.setState({ ref });
}
componentWillUnmount() {
const { ref } = this.state;
if (ref !== null) {
ref.off();
}
}
render() {
const { data } = this.state;
return (
<WrappedComponent data={data} {...this.props} />
);
}
};
};
但在我构建应用程序的方式中,我最终在同一个引用上创建了两个侦听器,当我调用 ref.off() 时,我失去了两个侦听器,这不是预期的行为。
事情是这样发生的:
1. already 2. push configview into stack 3. has another
has listener and adds another listener listener
------------ ------> --------------
| | | |
| | | |
| listview | | configview |
| screen | | screen |
| | | |
------------- <------- ---------------
5. doesn't have 4. pops configview from stack
listener anymore and removes both listeners
基本上,有什么方法可以从 firebase 上的引用中仅删除特定的侦听器?
【问题讨论】:
标签: javascript firebase react-native firebase-realtime-database