【发布时间】:2016-04-16 08:53:53
【问题描述】:
我正在尝试使用 ReactFire 来获取用户特定的数据并显示它。我已经按照Firebase's denormalized suggestions 组织了我的数据。下面看一下数据的结构。
"notes" : {
"n1" : {
"note" : "[noteData]",
"created_at" : "[date]",
"updated_at" : "[date]",
}
},
"users" : {
"userOne" : {
"name" : "[userName]",
"notes" : {
"n1" : true
}
}
}
我可以在没有 ReactFire 的情况下使用以下代码从我的应用程序中读取和写入数据,只需使用 FB API(每次在记事本中键入击键时都会运行updateCode):
componentWillMount: function() {
firebaseRef.child('users/' + authData.uid + '/notes').orderByChild('date_updated').on("child_added", function(noteKeySnapshot) {
// Take each key and add it to an array
usersNotesKeys.push(noteKeySnapshot.key());
// For each note key, go and fetch the Note record with the same key
firebaseRef.child('notes/' + noteKeySnapshot.key()).once("value", function(noteSnapshot) {
// Add that full note object to an array + the parent key
var data = noteSnapshot.val();
usersNotesList.push({
'created_at': data.created_at,
'updated_at': data.updated_at,
'note': data.note,
'key': noteKeySnapshot.key()
});
});
this.setState({
usersNotesList: usersNotesList
});
}.bind(this));
},
updateCode: function(newCode) {
firebaseRef.child('notes/' + this.state.item['key']).on('value', function(noteSnapshot, prevChildKey) {
// Look through the current note list and find the matching key and update that key with the new content.
var data = noteSnapshot.val();
updatedItem = {
'created_at': data.created_at,
'updated_at': data.updated_at,
'note': data.note,
'key': noteSnapshot.key()
};
// console.log(updatedItem);
this.setState({
item: updatedItem
});
}.bind(this));
}
从技术上讲,该代码有效。但是速度很慢。
当我使用 ReactFire 直接写入便笺时,无需通过用户,它工作得很好,而且更简单。但我需要说明是用户特定的。所以我想找到一种方法来使用这种数据结构的 ReactFire。这可能吗?
【问题讨论】:
-
您为什么要在
componentWillMount上向usersNoteKeys和usersNotesList推送? -
@arve0 - 好问题。
usersNotesList是用户笔记的数组,一旦我去 FB 抓取它们。因此,该函数获取每个音符并将音符数据推送到usersNotesList数组中,然后可以在状态中访问。 -
在
componentWillMount中写入数据有腥味。另外:我在updateCode()中没有看到任何数据库更新。但是,我确实看到updateCode()执行的每次,您都在附加一个新的侦听器。如果updateCode()被反复调用,你最终会得到很多听众。 -
谢谢,弗兰克!澄清一下,
componentWillMount中没有写入 FB 数据库,只是写入本地数组。updateCode()中的数据库更新代码是:noteRef.update({ "note": this.state.code, "updated_at": Firebase.ServerValue.TIMESTAMP });如果不附加新的侦听updateCode(),您将如何更新代码? -
@dave-dawson 啊哈,没有看到它在任何地方定义。删除
updateCode中的事件监听器并将componentWillMount中的once事件更改为value事件怎么样?那不会做同样的事情吗?