javascript - react this.setState 不是一个函数

标签 javascript reactjs

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

TypeError: this.setState is not a function

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

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>
        );
    }
});

最佳答案

回调是在不同的上下文中进行的。您需要 bindthis 以便在回调中访问:

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) 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');

关于javascript - react this.setState 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31045716/

相关文章:

html - 背景图像和图标未在背景图像上对齐的问题

javascript - React Redux &lt;input&gt; onChange 更新值问题

javascript - 如何使用 Ajax 调用将列表传递给 Spring MVC Controller

javascript - 替换除匹配字符串之外的所有内容 - JS Regex

php - 防止用户在上传过程中关闭浏览器/更改 url

javascript - React Native 通过嵌套导航器传递 props

javascript - 当我切换到另一个导航系统时,CSS 类消失了

javascript - 如何重定向 Google Chrome 扩展中的某些页面?

javascript - 标题标题不会随着底部导航而改变 React Native Navigation v5

javascript - 当我使用 renderItme 时,react-native-snap-carousel 返回 "Cannot read property ' concat' of undefined”