我是新來的反應,所以我敢肯定我失去了一些基本的東西。我得到這個未定義,因此不能讀取屬性'setState'試圖設置狀態在函數的返回中調用fetch,我做錯了什麼?注意我從onClick調用MyAction並且響應數據沒有問題。反應setState裏面的功能這是undefined
var ItemComponent = React.createClass({
getInitialState: function() {
return {
the_message: "call that API!"
};
},
doFetch: function() {
var obj = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
return fetch('http://localhost:1337/site/test', obj).then(function(response) {
return response.json();
}).then(function(data) {
return data;
}).catch((error) => {
console.error(error);
});
},
MyAction: function(){
this.doFetch().then(function(response){
this.setState({
the_message: response.message
});
})
},
render: function() {
return (
<div>
<div>{this.props.title}</div><br></br>
<div>{this.props.price}</div><br></br>
<div onClick={this.MyAction}>{this.props.qty}</div>
</div>
);
}
});
可能重複[「這個」關鍵字是如何工作的?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) –