0

因此,我遇到了一個奇怪的問題,也許我在這裏做錯了什麼,但之前我沒有遇到過這個問題,而且我的應用程序中充滿了類似的代碼。代碼在componentDidMount中執行,但在其他函數中不執行

基本上我試圖做一個簡單的Firestore get()函數附加到按鈕onPress。由於某些原因,代碼不運行,或者如果是我沒有得到任何反饋。如果我將相同的代碼放在componentDidMount中,它會運行併爲我提供數據庫快照。

下面是兩個有問題的代碼。

更新當前綁定我使用

this.usersRef = firebase.firestore().collection('users'); 

componentDidMount() { 
    this.usersRef 
     .get() 
     .then((snapshot) => { 
      console.log('TEST didMount snapshot', snapshot); 
     }).catch((error) => { 
      console.log(error) 
     }); 
} 


    submitSearch() { 
     console.log('submitSearch') 
     this.usersRef 
      .get() 
      .then((snapshot) => { 
       console.log('TEST submitSearch snapshot', snapshot); 
      }).catch((error) => { 
       console.log(error) 
      }); 
} 

的submitSearch就是從這裏被稱爲

  <Button style={{marginTop: 3, marginBottom: 8}} primary onPress={() => this.submitSearch()}> 
       {strings.search} 
      </Button> 

所以我已經嘗試了很多東西在這裏,我可以」 t似乎弄清楚爲什麼代碼在submitSearch函數中不起作用。我從這個函數看到的唯一的事情是控制檯日誌說提交搜索。

任何想法,將不勝感激!謝謝。

+0

你有綁定submitSearch功能嗎? –

+0

我相信如此,我試過了幾種不同方式的綁定。如果它沒有被正確綁定,它會拋出一個錯誤不是嗎? –

+0

是的,我認爲是這樣的 –

回答

0

問題在於函數綁定的方式。

我本來在構造函數如下: this.submitSearch = this.submitSearch.bind(this)

,並與

onPress={this.submitSearch}

調用它的按鈕組件我刪除了構造結合,只是使用按鈕以下組件:

onPress={() => this.submitSearch()} 

我以爲我曾經做過已經!但我可以證實這可以解決這個問題。奇怪的是,雖然沒有任何警告或錯誤,但似乎是一種情況,他們會有所幫助,而不僅僅是不運行代碼。