我目前初始化我的狀態是這樣的:使用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