setState: 只能更新一个已挂载或正在挂载的组件 react native /undefined is not an object
setState: can only update a mounted or mounting component react native /undefined is not an object
只要我的互联网连接不好,我就会不断收到此警告(我不确定这是否是导致这种情况发生的正确原因)。
我在反应本机应用程序 (iOS/android) 中显示来自 Firebase 数据库的数据的页面中得到了这个。
PS:我不考虑制作离线模式(这不是必需的)。
我正在与您分享我在这些页面之一中使用的代码(所有页面都非常相似)
代码
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
})
};
this.itemsRef = this.getRef().child('path');
}
getRef() {
return firebaseApp.database().ref();
}
componentDidMount() {
this.listenForItems(this.itemsRef);
}
listenForItems(itemsRef) {
itemsRef.on('value', (snap) => {
if (snap.val()) {
var items = [];
snap.forEach((child) => {
items.push({
text : child.val().text,
title: child.val().title,
key: child.key
});
});
this.setState({dataSource: this.state.dataSource.cloneWithRows(items)});
}
});
}
render() {
return (
<View>
<ListView
automaticallyAdjustContentInsets={true}
dataSource={this.state.dataSource}
renderRow={this._renderItem.bind(this)}/>
</View>
);
}
_renderItem(item) {
return (
<View>
<Text>{item.title}</Text>
<Text>{item.text}</Text>
</View>
);
}
}
这是我不断收到的警告:
它确实提到了组件的名称,但我仍然不知道这可能是什么原因
更新: 我尝试了这个建议的解决方案:
componentWillUnmount() {
this.itemRef.off();
}
事实上,我有一个从一个页面切换到另一个页面的后退按钮(每个页面都有自己的路径和从 Firebase 中提取的数据,但代码相似),我得到这个错误:this.itemRef
is different in每一页。
但我收到此错误:
任何想法或建议..谢谢
当您使用 on()
订阅引用时,您将在修改数据库路径时收到通知,卸载组件时也会收到通知。为了防止出现此警告,您必须 call off()
在 componentWillUnmount
上引用相同的数据库
componentWillUnmount() {
this.itemsRef.off();
}
只要我的互联网连接不好,我就会不断收到此警告(我不确定这是否是导致这种情况发生的正确原因)。 我在反应本机应用程序 (iOS/android) 中显示来自 Firebase 数据库的数据的页面中得到了这个。 PS:我不考虑制作离线模式(这不是必需的)。 我正在与您分享我在这些页面之一中使用的代码(所有页面都非常相似)
代码
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
})
};
this.itemsRef = this.getRef().child('path');
}
getRef() {
return firebaseApp.database().ref();
}
componentDidMount() {
this.listenForItems(this.itemsRef);
}
listenForItems(itemsRef) {
itemsRef.on('value', (snap) => {
if (snap.val()) {
var items = [];
snap.forEach((child) => {
items.push({
text : child.val().text,
title: child.val().title,
key: child.key
});
});
this.setState({dataSource: this.state.dataSource.cloneWithRows(items)});
}
});
}
render() {
return (
<View>
<ListView
automaticallyAdjustContentInsets={true}
dataSource={this.state.dataSource}
renderRow={this._renderItem.bind(this)}/>
</View>
);
}
_renderItem(item) {
return (
<View>
<Text>{item.title}</Text>
<Text>{item.text}</Text>
</View>
);
}
}
这是我不断收到的警告:
它确实提到了组件的名称,但我仍然不知道这可能是什么原因
更新: 我尝试了这个建议的解决方案:
componentWillUnmount() {
this.itemRef.off();
}
事实上,我有一个从一个页面切换到另一个页面的后退按钮(每个页面都有自己的路径和从 Firebase 中提取的数据,但代码相似),我得到这个错误:this.itemRef
is different in每一页。
但我收到此错误:
当您使用 on()
订阅引用时,您将在修改数据库路径时收到通知,卸载组件时也会收到通知。为了防止出现此警告,您必须 call off()
在 componentWillUnmount
componentWillUnmount() {
this.itemsRef.off();
}