代码之家  ›  专栏  ›  技术社区  ›  Ben Cavenagh

使用firebase数据装载前设置react组件的状态

  •  1
  • Ben Cavenagh  · 技术社区  · 6 年前

    componentWillMount(){
      const rootRef = fire.database().ref('groups')
      rootRef.limitToFirst(1).once('value', function(snap) {
        snap.forEach(function(child){
          var first = (child.val()).id;
          console.log(first);
          this.setState({ selectedGroupId: first });
        })
      });
    }
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Hemadri Dasari    6 年前

    试试这个。

    不要在循环中执行setState,这样会出现错误,因为您使用的是常规函数,所以请将其更改为如下所示的箭头函数。同时切换到componentDidMount方法,因为componentWillMount已弃用

      componentDidMount(){
          const rootRef = fire.database().ref('groups')
          rootRef.limitToFirst(1).once('value', snap => {
          let first = 0;
          snap.forEach(child => {
              first = (child.val()).id;
              console.log(first);
         })
         this.setState({ selectedGroupId: first });
         });
      }
    

    或者像这样绑定,如果你不喜欢使用箭头函数

       componentDidMount(){
             const rootRef = fire.database().ref('groups')
             rootRef.limitToFirst(1).once('value', function(snap) {
                  let first = 0;
                  snap.forEach(function(child){
                        first = (child.val()).id;
                        console.log(first);
                   }.bind(this));
                 this.setState({ selectedGroupId: first });
                }.bind(this));
         }
    

    开始使用let&常量而不是变量。

        2
  •  1
  •   seanulus    6 年前

    componentWillMount(){
      const rootRef = fire.database().ref('groups')
      rootRef.limitToFirst(1).once('value', (snap) => {
        snap.forEach((child) => {
          var first = (child.val()).id;
          console.log(first);
          this.setState({ selectedGroupId: first });
        })
      });
    }