反应 this.setState 不是一个函数 [英] React this.setState is not a function
问题描述
我是 React 的新手,我正在尝试编写一个使用 API 的应用程序.我不断收到此错误:
<块引用>TypeError: this.setState 不是函数
当我尝试处理 API 响应时.我怀疑这个绑定有问题,但我不知道如何修复它.这是我的组件的代码:
var AppMain = React.createClass({getInitialState:函数(){返回{名: " "};},componentDidMount:function(){VK.init(函数(){console.info("API 初始化成功");VK.api('users.get',{fields: 'photo_50'},function(data){如果(数据.响应){this.setState({//错误发生在这里名字:data.response[0].first_name});控制台信息(this.state.FirstName);}});}, 功能(){console.info("API 初始化失败");}, '5.34');},渲染:函数(){返回 (<div className="appMain"><标题/>
);}});
回调是在不同的上下文中进行的.您需要将 bind
绑定到 this
才能在回调中访问:
VK.api('users.get',{fields: 'photo_50'},function(data){如果(数据.响应){this.setState({//错误发生在这里名字:data.response[0].first_name});控制台信息(this.state.FirstName);}}.bind(this));
看起来你必须同时绑定 init
和 api
调用:
VK.init(function(){console.info("API 初始化成功");VK.api('users.get',{fields: 'photo_50'},function(data){如果(数据.响应){this.setState({//错误发生在这里名字:data.response[0].first_name});控制台信息(this.state.FirstName);}}.bind(this));}.bind(this), function(){console.info("API 初始化失败");}, '5.34');
I'm new in React and I'm trying to write an app working with an API. I keep getting this error:
TypeError: this.setState is not a function
when I try to handle the API response. I suspect it's something wrong with this binding but I can't figure out how to fix it. Here's the code of my component:
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>
);
}
});
The callback is made in a different context. You need to bind
to this
in order to have access inside the callback:
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));
EDIT:
Looks like you have to bind both the init
and api
calls:
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');
这篇关于反应 this.setState 不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!