首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >React this.setState不是一个函数

React this.setState不是一个函数
EN

Stack Overflow用户
提问于 2015-06-25 16:59:31
回答 15查看 421.5K关注 0票数 351

我是React的新手,我正在尝试编写一个使用API的应用程序。我一直收到这个错误:

TypeError: this.setState不是函数

当我尝试处理API响应时。我怀疑这个绑定有问题,但我不知道如何修复它。下面是我的组件的代码:

代码语言:javascript
复制
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>
        );
    }
});
EN

回答 15

Stack Overflow用户

回答已采纳

发布于 2015-06-25 17:01:00

回调是在不同的上下文中进行的。您需要通过bind连接到this才能在回调中访问:

代码语言:javascript
复制
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));

代码语言:javascript
复制
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');
票数 402
EN

Stack Overflow用户

发布于 2016-01-27 01:52:20

您可以使用ES6箭头函数来避免对.bind(这)的需要。

代码语言:javascript
复制
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);
        }

    });
票数 151
EN

Stack Overflow用户

发布于 2018-09-21 00:29:55

React建议在所有需要使用this而不是class而不是self function的方法中绑定this。

代码语言:javascript
复制
constructor(props) {
    super(props)
    this.onClick = this.onClick.bind(this)
}

 onClick () {
     this.setState({...})
 }

或者,您也可以使用arrow function

票数 50
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31045716

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档