从Firebase / React检索数据

时间:2018-11-24 21:38:01

标签: javascript firebase asynchronous firebase-realtime-database

我正在尝试从Firebase数据库中检索一个字段,但无法真正解决这个问题。

这篇文章帮助我了解了问题:https://medium.com/google-developers/why-are-firebase-apis-asynchronous-callbacks-promises-tasks-e037a6654a93。 我被卡住了,因为它是一个异步调用。

在日志1中,我得到了实际值,但在日志2中,我得到了[对象承诺]。 这是我的代码。首先是我要使用数据的部分。这是membership.status:

export const ExpenseList = (props) => (
  <div className="content-container">
    <div className="list-header">
      <div className="show-for-mobile">Podcasters</div>
      <div className="show-for-desktop">Podcaster</div>
      <div className="show-for-desktop">Details</div>
    </div>
    <div className="list-body">

      { console.log('Log 2.' + props.membership)}

      {
        props.membership === "active" ? (
            props.expenses.map((expense) => {
              return <ExpenseListItemSub key={expense.id} {...expense} />;
            })
          ) : (
            props.expenses.map((expense) => {
              return <ExpenseListItem key={expense.id} {...expense} />;
            })
          )
      }
    </div>
  </div>
);

const mapStateToProps = (state) => {
  return {
    expenses: selectExpenses(state.expenses, state.filters),
    membership: membershipS(state.membership) // modif Header
    }
  };

export default connect(mapStateToProps)(ExpenseList);

这是数据库调用

let currentUser = null;
let membeIsActive = null;
firebase.auth().onAuthStateChanged(firebaseUser => {
  if (firebaseUser) {
    currentUser = firebaseUser.uid;
  }
  });

  export default (membership) => {
    var firstName = "unknown"

    var promise = firebase.database()
        .ref(`/users/${currentUser}/pro-membership`)
        .once('value');

    return promise.then(snapshot => {
        firstName = snapshot.val().status;
        console.log('Log 1.' + firstName);
    })

    };

尝试使用async / await失败。

0 个答案:

没有答案