簡體   English   中英

為什么 firestore where 子句不適用於 state?

[英]Why is firestore where clause not working with state?

我正在嘗試使用 react js 中的 where 子句從 firestore 過濾文檔。 但是,當我在 where 子句中使用 state 變量時它不起作用但是當我提供實際字符串時它開始工作

不工作

firebase.firestore().collection('Partners')
    .where("Email",'==',this.state.currentUser).get().then( querySnapshot => {
      querySnapshot.forEach(doc => {

        this.setState({
          Theatre:doc.data().Theatre
        })

    })
})

在職的

firebase.firestore().collection('Partners')
    .where("Email",'==',"test@test.com").get().then( querySnapshot => {
      querySnapshot.forEach(doc => {

        this.setState({
          Theatre:doc.data().Theatre
        })

    })
})

任何幫助,將不勝感激。 謝謝你。

編輯我什至嘗試過console.log(this.state.currentUser==='test@test.com')並且它實現了。 然而 where 子句不適用於 state 變量

可能是您的 state 變量的問題,例如setState的異步效果或任何其他可能的原因。

確保您的 state 變量currentUser有一個值。 為了安全起見,請在if條件下運行此 function:

if(this.state.currentUser){
 firebase.firestore().collection('Partners')
     .where("Email",'==',this.state.currentUser).get().then( querySnapshot => {
       querySnapshot.forEach(doc => {

         this.setState({
           Theatre:doc.data().Theatre
         })

     })
 })
}

對於調試,請嘗試控制台記錄它。

React state is asynchronous you do get a state value in a console but by the time firestore query is ran because it is also asynchronous your state is somehow getting override or maybe your the page is getting refreshed and state is being set again.

我遇到了同樣的問題,然后我檢查了我的頁面是否正在刷新,並且我丟失了我設置的 state,即使我確實在 console.log() 中得到了它,但是當我在那里運行查詢的 Firestore 時,已經沒有 state。

您需要在此處提供整個代碼,以便我們查看。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM