JSON Firebase 和 React Native Flatlist 之间的格式

JSON format between Firebase and React Native Flatlist

这是 Firebase 实时数据库中存储的数据

"Users" : {
  "Joe" : {
    "name" : "xxx",
    "email" : "xxx"
 },
 "Matt" : {
    "name" : "xxx",
    "email" : "xxx"
 }
}

这是 React Native Flatlist 中需要的数据

 Users : [
  {
    id : "Joe"
    name : "xxx",
    email : "xxx",
  },
  {
    id : "Matt"
    name : "xxx",
    email : "xxx",
  }
]

componentDidMount()的某个地方..

firebase.database("Users").ref().once('value').then(function(snapshot) {
    var arr = _.values(snapshot.val());
    this.setState({ users: JSON.stringify(arr) });
})

在渲染 Flatlist 中:

   <FlatList
           extraData={this.props}
           data={this.props.users}
           keyExtractor={(item, index) => index.toString()}
           renderItem={({ item }) => (
    ...

我如何使用 firebase.database().ref() 和 return flatlist 中需要的数据是什么样的?

您可以尝试这样的操作:

我的第一个constructor

constructor(props) {
    super(props);

    this.state = {
        arrData:[]
    };
}

然后从 firebase 获取数据

var ref = firebase.database().ref("Users"); //Here assuming 'Users' as main table of contents   

ref.once('value').then(snapshot => {
    // console.log(snapshot.val());

     // get children as an array
     var items = [];
     snapshot.forEach((child) => {
       items.push({
          id: child.val().id,
          name: child.val().name,
          email: child.val().email,
          phone: child.val().phone,
          status: child.val().status,
          user_type: child.val().user_type

       });
    });

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

现在您可以在 FlatListListView 中填充 arrData

希望对您有所帮助!

在这里,我得到了用户在对象中发布的问题的数组,然后我创建了一个数组,然后将该数组分配给变量。

componentDidMount(){
  let user =  firebase.auth().currentUser ;
  let uid = user.uid;
  firebase.database().ref('Problems').orderByChild('userid').equalTo(uid)
  .once('value' )
  .then(snapshot => {
     // console.log(snapshot.val());
    var items = [];
     snapshot.forEach((child) => {
       items.push({
          id: child.key,
          problemDescription: child.val().problemDescription,
          problemTitle: child.val().problemTitle,
          problemstatus: child.val().problemstatus,
          timeanddate: child.val().timeanddate,
       });
    });
    console.log(items);
    this.setState({problmes: items}); 
    this.setState({isloading:false});
  })
  .catch(error => console.log(error));

}