JavaScript Promise-对象已定义,但未定义特定属性

时间:2018-09-05 21:38:00

标签: javascript reactjs firebase object firebase-realtime-database

我正在尝试从Firebase获取数据。我将数据作为对象接收,并显示了我想要的数据。但是,当我尝试从Object属性获取特定值时,它表示未定义。我在做错什么或我想念什么?

export const createChat = () => {
  return async dispatch => {
    dispatch({ type: CREATE_SINGLE_CHAT });
    const creator = firebase.auth().currentUser.uid;
    const userRef = firebase.database().ref(`/users/${creator}`);
    const currUser = await userRef.once('value');
    console.log(currUser);
    console.log(currUser.name);
  };
};

这是console.log:

23:30:58  // currUser
Object {
  "email": "a@b.de",
  "is24Hours": true,
  "name": "Alex",
}
23:30:58 // currUser.name
undefined

我正在使用带有Redux和Redux-Thunk的React Native,以及来自firebase的实时数据库作为数据库。

1 个答案:

答案 0 :(得分:0)

正如Max Brodin所提到的,我忘了使用firebase的val()方法: firebase.google.com/docs/database/web/read-and-write

工作代码:

export const createChat = () => {
  return async dispatch => {
    dispatch({ type: CREATE_SINGLE_CHAT });
    const creator = firebase.auth().currentUser.uid;
    const userRef = firebase.database().ref(`/users/${creator}`);
    const currUser = await userRef.once('value');
    console.log(currUser);
    console.log(currUser.val().name); // here is the change
  };
};