Reactjs承诺从firebase加载用户数据

问题描述 投票:0回答:1

在我检查用户是否已登录之后,我正在尝试从我的firebase加载数据。我试图用承诺来做,但是我得到了这个错误

whenAuth.then不是函数

我还尝试从componentDidMount()render()方法加载数据,但查询没有等待用户的初始化。

componentWillMount() {
  let whenAuth =
       firebase.auth().onAuthStateChanged((user) => {
      const userProfile = firebase.auth().currentUser;
      if(user){
        this.setState({
          authenticated: true,
          name : userProfile.displayName,
          email : userProfile.email,
          uid : userProfile.uid,
        })
      } else {
        this.setState({
          authenticated: false,
        })
        return <Redirect to="/"/>
      }
    })
  whenAuth.then(()=>{
      const previousCards = this.state.cards;
        firebase.database().ref().child('app').child('cards')
        .orderByChild('uid').equalTo(this.state.uid)
           .once('value', snap => {
             snap.forEach(childSnapshot => {
             previousCards.push ({
               id: childSnapshot.key,
               cardDesc: childSnapshot.val().cardDesc,
               cardPreis: childSnapshot.val().cardPreis,
               cardHeading: childSnapshot.val().cardHeading,
               cardBewertung: childSnapshot.val().bewertung,
               cardImage: childSnapshot.val().imageUrl,
               standOrt: childSnapshot.val().ort,
               imageArr: childSnapshot.val().imageArr,
             })
             this.setState ({
               cards: previousCards,
             })
           })
         })
       })

  }

在此先感谢您的帮助

javascript reactjs firebase ecmascript-6 promise
1个回答
0
投票

您的方法不会返回承诺。因此解决方案是在回调中调用您的逻辑。

myMethod() {
  const previousCards = this.state.cards;

  firebase.database().ref().child('app').child('cards')
    .orderByChild('uid').equalTo(this.state.uid)
    .once('value', snap => {
      snap.forEach(childSnapshot => {
        previousCards.push ({
          id: childSnapshot.key,
          cardDesc: childSnapshot.val().cardDesc,
          cardPreis: childSnapshot.val().cardPreis,
          cardHeading: childSnapshot.val().cardHeading,
          cardBewertung: childSnapshot.val().bewertung,
          cardImage: childSnapshot.val().imageUrl,
          standOrt: childSnapshot.val().ort,
          imageArr: childSnapshot.val().imageArr,
        })
        this.setState ({
          cards: previousCards,
        })
      })
    })
  }

componentWillMount(){
  let whenAuth = firebase.auth().onAuthStateChanged((user)=>{
    const userProfile = firebase.auth().currentUser;

    if(user){
      this.setState({
        authenticated: true,
        name : userProfile.displayName,
        email : userProfile.email,
        uid : userProfile.uid,
      })
    } else {
      this.setState({
        authenticated: false,
      })
      return <Redirect to="/"/>
    }

    // --> your function ends here
    this.myMethod();
  })
}
© www.soinside.com 2019 - 2024. All rights reserved.