React this.setState は関数ではありません 質問する

React this.setState は関数ではありません 質問する

サードパーティのAPIで動作するアプリを作成しようとすると、このエラーが発生し続けます

TypeError: this.setState は関数ではありません

API レスポンスを処理しようとしたとき、このバインディングに何か問題があるのではないかと考えていますが、修正方法がわかりません。これが私のコンポーネントのコードです:

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

ベストアンサー1

コールバックは別のコンテキストで行われます。コールバック内にアクセスするには、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));

init編集:と の両方の呼び出しをバインドする必要があるようですapi:

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

おすすめ記事