【发布时间】:2017-02-27 11:39:49
【问题描述】:
我目前这样初始化我的状态:
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)”就可以了。我不想将其标记为答案,因为我可以使用一些关于性能的建议:)
标签: javascript reactjs firebase firebase-realtime-database