我正在學習React,所以對我很溫和,我是一名新手。我有這個組件:React - 在React組件上使用變量時出錯
import React from 'react';
import HttpHandler from './../services/HttpHandler';
import Podcast from './Podcast/Podcast';
class Master extends React.Component{
constructor(){
super();
this.api = new HttpHandler();
this.podList = this.api.getAllPodcasts();
this.http = "";
this.api.getHttpResponse(function(responseData){
var datos = responseData;
this.http = datos;
}, function(error){
this.http = error;
});
}
render(){
return (
<div>
<h1>Master</h1>
<ul>
{this.podList.map((podcast) => <li>{podcast}</li>)}
</ul>
<p>API Response: {this.http}</p>
</div>
);
}
}
// ========================================
export default Master;
這個組件使用HttpHandler clads啓動一個XmlHttpRequest GET。在成功響應時,我執行回調函數,除了當我嘗試處理響應時,所有的都是完美的,var this.http
未定義,我得到TypeError: undefined is not an object (evaluating 'this.http = datos')
。很明顯,我有一個不好的變量聲明,這將實現的方式?
我想我理解剛纔的狀態。仍然得到錯誤,但是這次'TypeError:undefined不是一個對象(評估'this.setState')',這可能是引用了'getHttpResponse()'中的匿名函數。 – LordVermiis
的確如此,這是一個範圍問題,我在調用getHttpResponse和內部的'that.setState'之前解決了它添加'var that = this'的問題。請在您的回覆中更改它以標記爲正確的回覆。歡迎您! – LordVermiis
是的,我忘記了:)沒問題,狀態既是最重要的,也可能是令人困惑的(至少在最初)React的方面。此外,如果您的應用程序增長,您應該查看[Redux](http://redux.js.org/docs/introduction/)。 –