【问题标题】:Populate listview from firebase. Different paths从 firebase 填充列表视图。不同的路径
【发布时间】:2019-02-23 15:56:59
【问题描述】:

我的数据库是这样的:

我知道如何获取 genUserID 和 genUserID2 并将信息渲染到 Flatlist。但是我怎样才能向一个fatlist 提出两个请求呢? 我想从 eventAttenders/2188058178082419 获取 ID,然后从用户数据库中获取名称。用户 ID 来自之前的请求。

我的代码:

 constructor(props) {
      super(props);
      this.state = {
          arrData:[]
      };
  }

  componentDidMount = () => {

  var ref = firebase.database().ref("eventAttenders/2188058178082419");

  ref.once('value').then(snapshot => {
       var items = [];
       snapshot.forEach((child) => {
         items.push({
            id: child.val().id,
            name: child.val().name,
            email: child.val().yks,
         });
      });

      this.setState({ arrData: items});
  });

  }

【问题讨论】:

    标签: firebase react-native react-native-flatlist


    【解决方案1】:

    嗯,如果正确理解您的问题,简单的解决方法是先获取所有 id,然后使用循环,再获取一个用户列表引用并获取数据。

    constructor(props) {
          super(props);
          this.state = {
              arrData:[]
          };
      }
    
      componentDidMount = () => {
    
         var ref = firebase.database().ref("eventAttenders/2188058178082419");
         var items = [];
         ref.once('value').then(snapshot => {
           snapshot.forEach((child) => {
             const { id } = child;
             console.log(id) //make sure you are getting two ids genUserID and 
             // genUserID2 from 2188058178082419 ref
             firebase.database().ref(`users/${id}`).once('value').then(childsnapshot => {
           childsnapshot.forEach(keys => {
             console.log(keys);
             items.push({
                name: keys.name,
                phone: keys.phone,
             });
          });
    
         });
    
          this.setState({ arrData: items});
      });
    
      }
    

    【讨论】:

    • 出现错误:TypeError: item.forEach is not a function
    • 你能把console.log(snapshot)发给我看看你是否得到2188058178082419的数据吗?可能你需要做 snapshot.forEach。在没有看到数据的情况下很难盲目地判断。 :) 但你的想法对吗?
    • 我看到了这个问题。所以 forEach 需要一个数组。但是对象中的项目。所以 console.log(item) 看看这是否真的是一个对象。然后用for (let id in item)替换forEach然后使用id
    • 我将 "item.forEach((child) => {" 更改为 " snapshot.forEach((child) => {" 然后在 "this.setState( { arrData: items});"。截图在这里:imgur.com/a/8MH85G6
    • 那你就做吧,items.forEach((child) => { const { id } = child; console.log(id) //make sure you are getting two ids genUserID and // genUserID2 from 2188058178082419 ref firebase.database().ref(users/${id}).once('value').then(childsnapshot => { snapshot.forEach((details) => { console.log(details)
    猜你喜欢
    • 2010-11-12
    • 2011-09-18
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多