简体   繁体   English

在React中从Firebase获取用户对象属性

[英]Get user object properties from Firebase in React

I have a user db in Firebase that uses the unique user id as the Key and within that key/value pairs like name: 'jane doe', email: 'jane@doe.com', etc. What I want to do is map the object and get the key values within. 我在Firebase中有一个用户数据库,该数据库使用唯一的用户ID作为键,并在该键/值对中,例如名称:“ jane doe”,电子邮件:“ jane@doe.com”等。我要做的是映射对象并获取其中的键值。 I'm able to get the Key (user id), but not the object key value pairs. 我可以获取键(用户ID),但不能获取对象键值对。 Here's my code: 这是我的代码:

  export default class Home extends Component {

    constructor(props) {
     super(props);

     var users = {};
     this.state = { users };
   }

   componentDidMount() {
    const dbRoot = firebaseDb.database().ref().child('users');

    dbRoot.on('value', snap => {
     const dbUsers = snap.val(); 

     this.setState({
       users: dbUsers
     });
   });
}


  render() {
    return (
      <div>
        <div>
          {Object.keys(this.state.users).map(function(user, i) {
            return <div key={i}>Key: {user}, Value: {user.name}</div>;
          })}
        </div>
    </div>);

  }

}

user.name comes back undefined. user.name返回未定义。 I've tried using this.state.users.name but I get a "state is undefined" message. 我尝试使用this.state.users.name,但收到“状态未定义”消息。 Can someone point me in the right direction. 有人可以指出我正确的方向。 Thanks! 谢谢!

You have two main problems with your code. 您的代码有两个主要问题。 The first is that you cannot access this.state inside the callback of your map() function because this is bound to that function and not to the whole class. 首先是您无法在map()函数的回调内部访问this.state ,因为this绑定到该函数而不是整个类。 There are a couple of ways to keep the this variable bound to the class but the cleanest way is to use the Arrow function syntax. 有两种方法可以使this变量绑定到类,但最干净的方法是使用Arrow函数语法。

Once you do that, you will still have a problem. 一旦这样做,您仍然会遇到问题。 You are using Object.keys which will only map over the keys of your result, but you are treating it as if it will pass the whole user object to the function. 您正在使用Object.keys,它将仅映射结果的键,但是您将其视为将整个用户对象传递给函数的方式。 In order to access the user object inside of your callback function, you will need to use the bracket notation with the key. 为了访问回调函数内部的用户对象,您将需要在括号中使用带键的符号。

With those two things in mind, your code should look something like this: 考虑到这两点,您的代码应如下所示:

{Object.keys(this.state.users).map(key => {
    return <div key={key}>Key: {key}, Value: {this.state.users[key].name}</div>;
})}

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

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