Firebase会做出反应,从连接的集合中获取数据

问题描述 投票:0回答:1

我正在使用Firebase和React,我有这些集合:

enter image description here

所以它就像sheets/userId/sheetId/sheetData

我如何得到最后两张(在这个例子中只有两张),以及来自/sheetsData的所有数据,格式很好,所以我可以将它存储在Redux商店中。谢谢

reactjs firebase firebase-realtime-database redux nosql
1个回答
1
投票

首先,你需要获得userID ....有很多方法可以做到这一点。以下是我个人使用的两个例子。

 // ********* Add a listener from the database to monitor whos logged in. *********
firebase.auth().onAuthStateChanged((user) => {
  // ********* If a user is logged in firebase will return the user object. THEY ARE NOT LOGGED IN THOUGH *********
  if (user) {
    console.log('onAuthStateChanged', user)
    // ********* Then we call an official Firebase function through actions, this would probably be getSheets() for you *********
    this.props.loginRequest(user);
  } else {
    console.log('No user signed in')
  }
});

// ********* After logging in the found user from above we need to set them to redux store *********  
let signedInUser = firebase.auth().currentUser;

if (signedInUser) {
  this.props.loginRequest(signedInUser);
  console.log('currentUserSignedIn', signedInUser)
} else {
  console.log('no active user', signedInUser)
}

获取用户ID后,您可以调用redux操作来获取此用户的快照,其中所有工作表都在对象对象中。

firebase.database().ref('users/' + user.uid).once('value').then(function (snapshot) {
         // ******** This method is straight from their docs ********
          // ******** It returns whatever is found at the path 
          xxxxx/users/user.uid ********
        let username = snapshot.val();
         console.log(' FOUND THIS USER FROM THE DB', username);
        // now dispatch whatever redux store action you have to store the user 
          information
        dispatch(userSet(username))
         })
.catch((err) => console.log(err));

最后,我建议将工作表存储为一个对象数组,因为目前看起来你正在使用firebase的push方法,它为每个新工作表创建唯一的ID。这使得对它们的操作变得困难,因为firebase将向您返回一个对象对象,您无法在不知道每个唯一ID的情况下使用.map,.filter或.forEach。

以下是我使用firebase登录https://github.com/GavinThomas1192/motoMechanicMeeKanic/blob/master/App/Actions/auth-actions.js的方法

我喜欢在本地打包对象并设置一次以避免火层深度嵌套。

© www.soinside.com 2019 - 2024. All rights reserved.