2017-06-26 46 views
0

我真的不知道爲什麼這不起作用,因爲我已經花費了很多比平常更多的時間來修復它。問題是我正在使用axios進行REST調用以獲取要呈現的數據。在塊內處理響應,即使我能夠檢索數據,'this'對象也無法引用正確的對象,並且出現錯誤。我dono爲什麼發生這種情況,但任何幫助將不勝感激。React的微小問題setState函數

將我的代碼片段放在下面。我已經嘗試在axios調用範圍之外保存這個上下文,並使用新的變量,但這也無濟於事。下面是我在我的控制檯得到錯誤

TypeError: _this2.setState is not a function

import React, {Component} from 'react'; 

import axios from 'axios'; 

import './RouteList.css'; 

class RouteList extends Component{ 
constructor(){ 
    super();   
    this.setState = { 
     allRoutes: {}, 
     selectedRoutes: {} 
    }; 
    }  

componentDidMount(){ 
    const that = this; 
    //Retrieve the SF-Muni route list   
    axios.get('http://webservices.nextbus.com/service/publicJSONFeed?command=routeList&a=sf-muni') 
     .then(response => { 
      console.log(response); 
      that.setState({ allRoutes: response.data.routes }); 
     }) 
     .catch((error) => { 
      console.log(error); 
     });    
} 

render(){ 
    return (
     <div className="transit-routes"> 
      {/*TODO-Code to render data.*/} 
     </div> 
    ); 
} 
} 
export default RouteList;` 

回答

3

的問題是要覆蓋在構造函數中setState方法,嘗試設置的初始狀態是這樣的:

this.state = { 
    allRoutes: {}, 
    selectedRoutes: {} 
}; 

而且,當使用箭頭函數時,不需要保存父範圍,該函數將在與外部函數相同的範圍內運行。

+0

謝謝一噸Crysfel。 絕對愚蠢的我在構造函數中做setState。 –

+0

hehehehe發生在我身上時長時間工作:)也許你需要一段時間休息xD – Crysfel

+3

另一個小事 - 如果你最終調用setState,確保你調用它像this.setState({foo: bar})而不是試圖將setState設置爲等於某些東西,這就是您使用'this.setState = {foo:bar}'所實際執行的操作 – istrupin