Join 在React中连接Firebase表

Join 在React中连接Firebase表,join,reactjs,firebase,Join,Reactjs,Firebase,我希望在React应用程序中显示来自Firebase DB的用户注释列表 在阅读完Firebase之后,我以他们推荐的扁平格式创建了我的数据库。数据结构如下所示: notes - [noteKey] - note: [noteData] - created_at: [date] - updated_at: [date] ... users - [userKey] - name: [userName]

我希望在React应用程序中显示来自Firebase DB的用户注释列表

在阅读完Firebase之后,我以他们推荐的扁平格式创建了我的数据库。数据结构如下所示:

    notes
    - [noteKey]
      - note: [noteData]
      - created_at: [date]
      - updated_at: [date]
    ...
    users
      - [userKey]
         - name: [userName]
         - notes
           - [noteKey]: true
           ... 
    ...
每个用户都有一个名为notes的数组,其中列出了他们所拥有的notes的noteKey

到目前为止,我已经能够获得完整的注释列表(来自所有用户,而不是我想要的),以及用户的注释键列表。我面临的问题是将这两者结合起来。我已经看到了,但我有一个更关注反应的问题:

连接发生在哪个React函数中?

现在,我的代码如下所示:

我认为这有两个问题

  • 当在
    componentWillMount
    中调用
    this.state.notesList.map
    函数时,该数组尚未填充Firebase数据,因此看起来像一个空数组并返回错误
  • 一旦我解出#1,我就不知道如何将特定于用户的注释放入它自己的数组中,该数组可由组件的其余部分访问 --

    • 应该在哪个React timeline函数中进行连接?
    • 如何将第二个表项(用户注释)添加到组件其余部分可以访问的数组中?

    您在这里使用的是异步库(),但您已经编写了同步代码

    这意味着
    base。syncState
    将向您的Firebase实例发出请求,同时,您的JavaScript将继续愉快地执行,无论是否有结果。因此,
    this.state.notesList.map
    将映射到一个空数组,因为JS的执行速度将比往返服务器的速度更快

    查看syncState方法的可用选项,有一个名为
    then
    的方法执行回调

    然后:(function-可选)当使用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'])
            }); 
          });
        }
      });
    }
    
    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'])
            }); 
          });
        }
      });
    }