【问题标题】:Firebase react, get data from connected collectionsFirebase 反应,从连接的集合中获取数据
【发布时间】:2017-12-16 12:39:53
【问题描述】:

我正在使用带有 React 的 Firebase,并且我有这些集合:

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

我如何从/sheetsData 获取最后两张表(在这个例子中只有两张表),它们的所有数据格式都很好,所以我可以将它存储在例如 Redux 存储中。谢谢

【问题讨论】:

    标签: reactjs firebase firebase-realtime-database redux nosql


    【解决方案1】:

    首先您需要获取用户ID....有很多方法可以做到这一点。以下是我个人使用的两个示例。

     // ********* 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。

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

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

    【讨论】:

    • 感谢您的回复,我一定会存储为对象数组,不知道为什么我没有这样做。
    猜你喜欢
    • 2021-06-28
    • 2018-03-24
    • 2021-07-23
    • 2021-03-05
    • 2020-05-24
    • 2021-07-25
    • 2020-09-07
    • 2021-06-01
    • 1970-01-01
    相关资源
    最近更新 更多