我是React的新手,我正在尝试编写一个使用API的应用程序。我一直收到这个错误:
TypeError: this.setState不是函数
当我尝试处理API响应时。我怀疑这个绑定有问题,但我不知道如何修复它。下面是我的组件的代码:
var AppMain = React.createClass({
getInitialState: function() {
return{
FirstName: " "
};
},
componentDidMount:function(){
VK.init(function(){
console.info("API initialisation successful");
VK.api('users.get',{fields: 'photo_50'},function(data){
if(data.response){
this.setState({ //the error happens here
FirstName: data.response[0].first_name
});
console.info(this.state.FirstName);
}
});
}, function(){
console.info("API initialisation failed");
}, '5.34');
},
render:function(){
return (
<div className="appMain">
<Header />
</div>
);
}
});
发布于 2015-06-25 17:01:00
回调是在不同的上下文中进行的。您需要通过bind
连接到this
才能在回调中访问:
VK.api('users.get',{fields: 'photo_50'},function(data){
if(data.response){
this.setState({ //the error happens here
FirstName: data.response[0].first_name
});
console.info(this.state.FirstName);
}
}.bind(this));
VK.init(function(){
console.info("API initialisation successful");
VK.api('users.get',{fields: 'photo_50'},function(data){
if(data.response){
this.setState({ //the error happens here
FirstName: data.response[0].first_name
});
console.info(this.state.FirstName);
}
}.bind(this));
}.bind(this), function(){
console.info("API initialisation failed");
}, '5.34');
发布于 2016-01-27 01:52:20
您可以使用ES6箭头函数来避免对.bind(这)的需要。
VK.api('users.get',{fields: 'photo_50'},(data) => {
if(data.response){
this.setState({ //the error happens here
FirstName: data.response[0].first_name
});
console.info(this.state.FirstName);
}
});
发布于 2018-09-21 00:29:55
React建议在所有需要使用this而不是class
而不是self function
的方法中绑定this。
constructor(props) {
super(props)
this.onClick = this.onClick.bind(this)
}
onClick () {
this.setState({...})
}
或者,您也可以使用arrow function
。
https://stackoverflow.com/questions/31045716
复制相似问题