反应setState里面的功能这是undefined
我是新来的反应,所以我敢肯定我失去了一些基本的东西。我得到这个未定义,因此不能读取属性'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>
);
}
});
您的内在承诺解析函数将不会有this
上下文。一种解决方法:
MyAction: function(){
this.doFetch().then(function(response){
this.setState({
the_message: response.message
});
}.bind(this))
},
了解更多关于this StackOverflow question。
Pefect,你第二次修复它,我不确定你在第一个项目中的建议是什么,因为这是我的代码保持不变?无论如何,只要它让我(5分钟),我就会接受你的回答。旁边的问题,我真的应该使用ES6语法是啊?在开始学习一些教程之后,我认为这个语法很长。 – edencorbin
双哎呀,我只是假定你在使用ES6类,第一次更新是无关紧要的。请把你的问题重复一次。 –
使用箭头功能(() => {}
)它保持最后一个范围(this
)照原样。
MyAction: function(){
this.doFetch().then((response) => {
this.setState({
the_message: response.message
});
});
},
这也适用,并显示我一个更好的语法,真棒,谢谢分配! – edencorbin
欢迎您 –
一个简单.bind(this)
将解决这一问题:
render: function() {
return (
<div>
<div>{this.props.title}</div><br></br>
<div>{this.props.price}</div><br></br>
<div onClick={this.MyAction.bind(this)}>{this.props.qty}</div>
</div>
);
通过添加.bind(this)
你保持你的函数内的范围。
可能重复[“这个”关键字是如何工作的?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) –