Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

javascript - 反应this.setState不是一个函数(React this.setState is not a function)

I'm new in React and I'm trying to write an app working with an API.(我是React的新手,正在尝试编写一个使用API??的应用程序。)

I keep getting this error:(我不断收到此错误:) TypeError: this.setState is not a function(TypeError:this.setState不是一个函数) when I try to handle the API response.(当我尝试处理API响应时。) 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> ); } });   ask by Ivan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The callback is made in a different context.(回调是在不同的上下文中进行的。)

You need to bind to this in order to have access inside the callback:(您需要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)); EDIT: Looks like you have to bind both the init and api calls:(编辑:看起来您必须绑定initapi调用:) 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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...