代码之家  ›  专栏  ›  技术社区  ›  Boss Nass

将数据推送到react native中的数组

  •  0
  • Boss Nass  · 技术社区  · 7 年前

    下面是日志

    [15:36:08] Get Ref https://xxxx.firebaseio.com/merchants
    [15:36:08] Gladiator Fitness
    [15:36:08] Array undefined
    

    这就是我试图执行的代码

    componentWillMount() {
        let initialLoad = true;
        this.setState({loading: true});
    
        var merchants = [];
    
        merchantsRef.once('value').then((snapshot) => { // here too!
          // ... and add it to the matches array
          console.log(snapshot.val().business_name)
          merchants.push({
            business_name: snapshot.val().business_name,
            _key: snapshot.key
          })
          console.log("Array " + merchants.business_name)
        }).catch((error) => { // If you are planning to use this here
          console.log('Error fetching merchant data:', error)
        })
    
        this.setState({
          data: merchants,
          loading: false
        })
    
        if (initialLoad) {
          this.setState({loading: false});
          initialLoad = false;
        }
    
      }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Community Mohan Dere    6 年前

    呼吁 setState 一定在房间里 value 回拨:

    var merchants = [];
    
    merchantsRef.once('value').then((snapshot) => { // here too!
      // ... and add it to the matches array
      console.log(snapshot.val().business_name)
      merchants.push({
        business_name: snapshot.val().business_name,
        _key: snapshot.key
      })
      console.log("Array " + merchants.business_name)
      this.setState({
        data: merchants,
        loading: false
      })
    }).catch((error) => { // If you are planning to use this here
      console.log('Error fetching merchant data:', error)
    })
    

    原因是回调是异步调用的,这意味着在代码中 设定状态 merchants 在填充数组之前调用数组。


    查看流量的最简单方法是使用几个位置良好的测井语句:

    console.log("Before starting to load");
    merchantsRef.once('value').then((snapshot) => { 
      console.log("Data loaded");
    })
    console.log("After starting to load");
    

    运行此代码时,输出为:

    在开始加载之前

    开始加载后

    数据加载

    设定状态

        2
  •  0
  •   QuokMoon    7 年前

    您的数据已在数组中,请检查 console.log("Array " + merchants.business_name) undefined 导致访问无效元素。

    console.log("Array " + merchants[0].business_name) or 
    console.log("Array " + merchants)
    
    推荐文章