gpt4 book ai didi

javascript - 使用React + Firebase,如何修改嵌套查询内的状态?

转载 作者:太空宇宙 更新时间:2023-11-04 15:58:30 25 4
gpt4 key购买 nike

我目前像这样初始化我的状态:

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”``

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

我的代码基于这个出色的答案,但没有成功: Firebase two-way relationships / Retrieving data

它在 componentDidMount 函数内运行。

关于如何影响国家有什么建议吗?

最佳答案

在 ES6 中,如果您使用粗箭头函数,这会更清晰,并且“this”将被绑定(bind),例如:

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

关于javascript - 使用React + Firebase,如何修改嵌套查询内的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42484872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com