我是React的新手,我正在尝试编写一个使用API的应用程序。我不断地发现这个错误:
TypeError:this.setState不是函数
当我尝试处理API响应时。我怀疑这个绑定有问题,但我不知道如何修复它。以下是我的组件的代码:
var-AppMain=React.createClass({
getInitialState:函数(){
返回{
名字:“
};
},
componentDidMount:function(){
init(函数(){
控制台信息(“API初始化成功”);
api('users.get',{fields:'photo_50'},函数(数据){
if(data.response){
this.setState({//)错误发生在此处
名字:data.response[0]。名字
});
console.info(this.state.FirstName);
}
});
},函数(){
控制台信息(“API初始化失败”);
}, '5.34');
},
render:function(){
返回(
<;div className=“appMain”>;
<;标题/>;
<;/div>;
);
}
});
回调是在不同的上下文中进行的。您需要将绑定到此,才能在回调中进行访问:
VK.api('users.get',{fields:'photo_50'},函数(数据){
if(data.response){
this.setState({//)错误发生在此处
名字:data.response[0]。名字
});
console.info(this.state.FirstName);
}
}.约束(这个);
编辑:
看起来您必须同时绑定init和api调用:
VK.init(函数(){
控制台信息(“API初始化成功”);
api('users.get',{fields:'photo_50'},函数(数据){
if(data.response){
this.setState({//)错误发生在此处
名字:data.response[0]。名字
});
console.info(this.state.FirstName);
}
}.约束(这个);
}.bind(this),function(){
控制台信息(“API初始化失败”);
}, '5.34');