我刚开始学习React,所以我肯定缺少一些基础知识。我在尝试在一个调用fetch的函数的返回中设置state时,得到了undefined,因此无法读取属性'setState'。请问我做错了什么?需要注意的是,我从onClick中调用MyAction,并且响应数据是正确的。
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>
);
}
});