当用户在单页应用程序中更改 View 时,我想断开 Firebase 引用的连接。当所述用户更改 View 时,我想获得对 firebase 的新引用,因为我只想要过滤数据,并且每个 View 过滤不同的数据。
当我更改 View 并更新一些数据时,就会出现问题。然后 react 会引发以下错误:
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op.
此错误在尝试更新未安装的组件时引用了其他 View 。这种情况不应该发生,因为我关闭了 componentWillUnMount 上的引用。
在这两个 View 中,我都有以下用于获取新引用的代码:
componentDidMount() {
// I have declared this.ref on the constructor so I can call off() on componentWillUnMount
this.ref = firebase.database().ref().child('mainNode').orderByChild('someProperty').equalTo('someValue');
this.ref.on('value', (snap) => {
let values = [];
snap.forEach((child) => {
let value = child.val();
let key = child.key;
const valueWithKey = update(value, {$merge: {key}});
values.push(valueWithKey);
});
// This is the offending line
this.setState({data: values});
});
}
这是我的 componentWillUnMount 代码:
componentWillUnMount() {
this.ref.off();
// I have also tried goOffline()
}
我做错了什么?
最佳答案
事实证明,正确的生命周期 Hook 名为 componentWillUnmount
而不是 componentWillUnMount
,这导致 React 无法执行该函数。
关于reactjs - react : Disconnecting firebase ref on componentWillUnMount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42389617/