2017-05-31 179 views
0

我的登錄組件出現問題,我使用的是cointainer模式,所以我有一個組件登錄管理api調用和一個管理輸入並警告用戶的DumbLogin關於我的服務器的響應。 我正在使用Axios來做api調用,它使用承諾來做到這一點,我也使用箭頭函數來避免這個問題,那是我在想什麼...... 因爲最後我有React Axios在setState後沒有渲染

TypeError: _this.setState is not a function

我試圖用一個變量self來解決這個問題,但那樣會導致相同的錯誤。

我該怎麼做?

axios(all) 
     .then((response) => { 
     console.log(response); 
      if (response.status === 200){ 
       this.setState({ 
        ...this.state, 
        spin: false, 
       }); 
       let data = response.data; 
       this.props.connect(data.username, data.email, data.token, data.partners); 
       this.props.router.push('panel'); 
      } 
     }).catch((error) => { 
      console.log(error.response); 
      this.setState({ 
       spin: false, 
       errorLogin: 'Username or password wrong', 
      }); 
     }); 

(自旋是布爾通知DumbLogin它應該或不顯示一個微調在等待我的服務器響應)

回答

0

這是因爲匿名函數內的thisthen內是而不是React組件的this

您需要爲正在調用ajax的函數綁定正確的this(Reac Component's this)。

例如。如果函數是:

fetchData(){ 
    axios(all).then(...).catch(...) 
} 

你可以在構造其綁定:

constructor(){ 
    this.fetchData = this.fetchData.bind(this) 
} 

無論其!

這是不推薦的解決方案,你通常會不想要做的Ajax調用的組件......你可能想終極版,mobx甚至是終極版,傳奇爲此,

+0

我不知道這事, 謝啦! 我用thunk結束了:) – Darakt