我希望在React应用程序中显示来自Firebase数据库的用户注释列表。
在阅读完Firebase recommended approach on structuring data后,我以他们推荐的展平格式创建了我的数据库。数据结构如下所示:
// Create the Data
List<Person> myData = new List<Person>();
myData.Add(new Person() { ID = 5, FirstName = "Jamie", LastName = "White", DateOfRegister = Convert.ToDateTime("Dec 25, 2015") });
myData.Add(new Person() { ID = 10, FirstName = "Mike", LastName = "Smith", DateOfRegister = Convert.ToDateTime("Jan 5, 2016") });
myData.Add(new Person() { ID = 25, FirstName = "Joe", LastName = "Yang", DateOfRegister = Convert.ToDateTime("Feb 28, 2016") });
// Pass the data to the dataGrid
dataGridView1.DataSource = myData;
每个用户都有一个名为notes的数组,其中列出了他们拥有的注释的noteKeys。
到目前为止,我已经能够获得完整的笔记列表(来自所有用户,而不是我想要的),以及用户的noteKeys列表。我遇到的问题是将这两者结合起来。我见过question about joining tables,但我有更多关于React的问题:
在哪个React函数中发生了连接?
现在我的代码看起来像这样:
notes
- [noteKey]
- note: [noteData]
- created_at: [date]
- updated_at: [date]
...
users
- [userKey]
- name: [userName]
- notes
- [noteKey]: true
...
...
我看到两个问题。
getInitialState: function(){
return {
notesList: []
};
},
componentWillMount: function() {
base = Rebase.createClass('https://appName.firebaseio.com');
base.syncState('notes', {
context: this,
state: 'notesList',
asArray: true,
queries: {
limitToLast: 20
}
});
this.state.notesList.map(function(item, i) {
base.child("notes/" + item['.key'] + "/note").on('child_added', function(snapshot) {
console.log(item['.key'])
});
});
},
中调用this.state.notesList.map
函数时,尚未使用Firebase数据填充数组,因此它看起来像一个空数组并返回错误。 -
答案 0 :(得分:1)
您正在使用异步库(re-base),但您已编写同步代码。
这意味着base.syncState
将触发对您的Firebase实例的请求,与此同时,您的JavaScript将继续愉快地执行,无论是否有结果。因此,this.state.notesList.map
将映射一个空数组,因为JS的执行速度比往返服务器要快。
查看可用于syncState方法的选项,有一个名为then
的执行回调的方法。
then :( function - optional)使用Firbase建立初始侦听器时将调用的回调函数。通常使用(使用syncState)将this.state.loading更改为false。
这让我觉得从Firebase获取数据后会触发它。
尝试在那里运行.map
,因为您实际上拥有所需的数据。
componentWillMount: function() {
base = Rebase.createClass('https://appName.firebaseio.com');
base.syncState('notes', {
context: this,
state: 'notesList',
asArray: true,
queries: {
limitToLast: 20
},
then: function() {
this.state.notesList.map(function(item, i) {
base.child("notes/" + item['.key'] + "/note").on('child_added', function(snapshot) {
console.log(item['.key'])
});
});
}
});
}