我目前初始化我的状态是这样的:使用React + Firebase,如何修改嵌套查询中的状态?
getInitialState: function() {
return {
conversations: {},
messages: {},
availableConversations: {}
}
},
如果我做这样的事情:
convosRef.on('value', snapshot => {
this.setState({ conversations: snapshot.val() });
});
它可以根据需要...但是:
users: {
uid: {
conversations: {
conversationid: true,
conversationid2: true
}
}
}
我顺利拿到预期目标:
userSnapshot.child('conversations').forEach(function (conversationKey) {
var conversationRef = database.ref('conversations').child(conversationKey.key);
conversationRef.on('value', function (conversationsSnapshot) {
var conversation = conversationsSnapshot.val();
conversationLoadedCount = conversationLoadedCount + 1;
myObject[conversationKey.key] = conversation;
// console.log(conversationKey.key);
//this.state.conversations = conversation;
if (conversationLoadedCount === conversationCount) {
console.log("We've loaded all conversations");
}
});
this.setState({ conversations: myObject });
});
});
但是。我收到两个错误,但不能影响状态: 第一个错误: `FIREBASE警告:异常是由用户回调抛出的。类型错误:无法读取null``的特性“的setState”
略有相似: Uncaught TypeError: Cannot read property 'setState' of null
我基于与没有成功任何这个优秀的答案我的代码: Firebase two-way relationships/Retrieving data
这里面运行componentDidMount function
。
关于如何影响国家的任何建议?
我找到了解决我的问题的方法,在每次firebase调用后添加“.bind(this)”就可以了,我不想将它标记为答案,因为我可以使用一些关于性能的建议:) – villancikos