简体   繁体   English

从Firebase一次设置多个变量的状态

[英]Setting state on multiple variables at once from firebase

I'm new to firebase and React. 我是Firebase和React的新手。 I've successfully retrieved user data from firebase with the following code: 我已使用以下代码从Firebase成功检索用户数据:

firebase.auth().onAuthStateChanged(firebaseUser => {
  if(firebaseUser) {
    const dbRoot = firebase.database().ref().child('users').child(firebaseUser.uid);
    const name = dbRoot.child('name');
    const bio = dbRoot.child('bio');

    name.on('value', snap => {
      this.setState({
        name: snap.val()
      });
    });

    bio.on('value', snap => {
      this.setState({
        bio: snap.val()
      });
    });

  } else {
    console.log("not logged in");
  }
});

} }

This works, but I'm looking for a better way to setState on all the values (name, bio, etc) without having to create multiple setState blocks like from above, and I haven't discovered it yet. 这可行,但是我正在寻找一种更好的方法来对所有值(名称,生物等)进行setState设置,而不必像上面那样创建多个setState块,而且我还没有发现它。 I have a lot of data to get from the user, so that code will get more cumbersome. 我有很多数据要从用户那里获取,因此代码将变得更加繁琐。 I'd like to do something like: 我想做类似的事情:

this.setState({
   name: snap.name.val(),
   bio: snap.bio.val(),
   email: snap.email.val()
});

Or whatever the best protocol is. 或任何最佳协议。 Can someone point me in the right direction? 有人可以指出我正确的方向吗? Thanks in advance. 提前致谢。

You don't have get the children 'name' and 'bio' separately from dbRoot: 您没有将孩子的“名称”和“生物”与dbRoot分开:

firebase.auth().onAuthStateChanged(firebaseUser => {
  if(firebaseUser) {
    const dbRoot = firebase.database().ref().child('users').child(firebaseUser.uid);

    dbRoot.on('value', snap => {
      const user = snap.val(); // snap is a child of 'users'
      this.setState({
        name: user.name,
        bio: user.bio,
        email: user.email
      });
    });

  } else {
    console.log("not logged in");
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM