在我检查用户是否已登录之后,我正在尝试从我的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,
})
})
})
})
}
在此先感谢您的帮助
您的方法不会返回承诺。因此解决方案是在回调中调用您的逻辑。
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();
})
}