2017-05-30 45 views
1

我試圖在ajax回調從REST API接收數據後setState的組件。這裏是我的部件構造TypeError:無法讀取未定義的屬性'setState'

constructor(props) { 
    super(props); 
    this.state = { posts: [] }; 
    this.getPosts = this.getPosts.bind(this); 
} 

代碼然後,我有一個componentDidMount方法,看起來像下面。

componentDidMount() { 
     this.getPosts(); 
} 

這裏是我的getPosts函數,我正在做ajax請求。

getPosts =() => { 
    $.ajax({ 
     type: 'get', 
     url: urlname, 
     success: function(data) { 
      this.setState({ posts: data }) 
     } 
    }); 
} 

我打算設置狀態,但出現以下錯誤。

this.setState is not a function 

不確定是什麼原因造成的。如果有人指出我正確的方向,那將會非常有幫助。提前致謝。

回答

4

綁定的回調函數,也讓this回調指向陣營組件的情況下,而不是回調函數內

getPosts =() => { 
    $.ajax({ 
     type: 'get', 
     url: urlname, 
     success: (data) => { 
      this.setState({ posts: data }) 
     } 
    }); 
} 
+0

非常感謝。 :) – Shadid

+0

沒問題,很高興有幫助。這是大多數人的常見錯誤。我會建議你在將來遇到這樣的錯誤時尋找約束力 –

1

該問題與丟失this的上下文有關。 請試試這個:

let self = this; 
getPosts =() => { 
    $.ajax({ 
     type: 'get', 
     url: urlname, 
     success: function(data) { 
      self.setState({ posts: data }) 
     } 
    }); 
} 

,或者您可以使用綁定:

getPosts =() => { 
     $.ajax({ 
      type: 'get', 
      url: urlname, 
      success: function(data) { 
       self.setState({ posts: data }) 
      } 
     }); 
    }.bind(this) 
0

您必須將上下文存儲到變量中,因爲「this」引用在回調中不可用。請嘗試以下解決方案:

getPosts =() => { 
let that=this; 
    $.ajax({ 
     type: 'get', 
     url: urlname, 
     success: function(data) { 
      that.setState({ posts: data }) 
     } 
    }); 
} 
相關問題