Javascript 使用React+;Firebase,如何修改嵌套查询中的状态?

Javascript 使用React+;Firebase,如何修改嵌套查询中的状态?,javascript,reactjs,firebase,firebase-realtime-database,Javascript,Reactjs,Firebase,Firebase Realtime Database,我当前初始化状态如下: getInitialState: function () { return { conversations: {}, messages: {}, availableConversations: {} } }, 如果我这样做: convosRef.on('value', snapshot => { this.setState({ conversations: snapshot.val()

我当前初始化状态如下:

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警告:用户回调引发异常。TypeError:无法读取null的属性“setState”``

略为相似:
未捕获类型错误:无法读取null的属性“setState”

我的代码基于这个极好的答案,但没有成功:

这在
componentDidMount函数
中运行


有没有关于如何影响国家的建议

我找到了解决我问题的办法,只是试着把它捆绑起来。 解决方案是每当我调用
firebase.database().ref()
时使用
bind(this)
。 这是最后一个片段,希望它能帮助像我这样的可怜的灵魂,如果有人有更好的答案或解释如何改进,请让我知道:

var myObject={}; usersRef.on('value',函数(userSnapshot){


在ES6中,如果您使用fat arrow函数,这将更加干净,“this”将被绑定,例如:

   userSnapshot.child('conversations').forEach((conversationKey) => {
            var conversationRef = database.ref('conversations').child(conversationKey.key);
            conversationRef.on('value', (conversationsSnapshot) => {

我找到了问题的解决方案。在每次firebase调用之后添加“.bind(this)”。我不想将其标记为答案,因为我可以使用一些关于性能的建议:)这就是我一直在寻找的见解。我在哪里可以读到更多关于这方面的信息?为什么这个“胖箭头”函数会自动绑定?
   userSnapshot.child('conversations').forEach((conversationKey) => {
            var conversationRef = database.ref('conversations').child(conversationKey.key);
            conversationRef.on('value', (conversationsSnapshot) => {