2017-10-09 32 views
1

我想弄清楚這種類型的錯誤來自哪裏,但我似乎無法找到它。也許我錯過了React的一個重要概念。反應:無法讀取屬性'getWeather'的未定義

我有一個天氣類陣營,如:

class Weather extends Component { 
    constructor(props) { 
    super(props); 

    this.state = { 
     cityName: "San Francisco", 
     temp: null, 
    } 
    } 

    getWeather(city) { 
    // does fetch request to openweathermap.org 
    } 

    handleSubmit(event) { 
    event.preventDefault(); 
    this.getWeather(this.state.cityName); 
    // this.state.cityName is updated as the user types 
    } 
} 

的問題是,每當我點擊提交按鈕,我得到一個錯誤關於我的GetWeather功能話說:

TypeError: Cannot read property 'getWeather' of undefined

任何建議?我嘗試綁定getWeather函數,但它沒有幫助。

+3

可能與handleSubmit沒有綁定的問題。你能告訴我們handleSubmit在哪裏使用嗎? –

+0

@NicholasTower就是這樣。下面的丹尼爾幫助我做到了。不知道我是如何錯過的,但正如我在下面所說的,我的組件比我的示例顯示的方式更大,所以我猜「容易」忽略了它。 – crescentfresh

回答

2

您需要綁定兩個getWeatherhandleSubmit

constructor(props) { 
    super(props); 

    this.state = { 
     cityName: "San Francisco", 
     temp: null, 
    } 

    this.getWeather = this.getWeather.bind(this); 
    this.handleSubmit = this.handleSubmit.bind(this); 
    } 
+0

就是這樣。我不知道我怎麼忘記也綁定handleSubmit。這個組件比我使用這個代碼更大,所以我完全忽略了這一點。基於這個錯誤,我有一種感覺,綁定失敗了,你馬上就知道了。謝謝!! – crescentfresh

1

你的情況this涉及到元素,而不是類。使用箭頭功能。

handleSubmit = (event) => { 
    event.preventDefault(); 
    this.getWeather(this.state.cityName); 
    // this.state.cityName is updated as the user types 
    } 
相關問題