1. ホーム
  2. javascript

[解決済み】React this.setStateは関数ではありません。

2022-01-25 05:54:03

質問

私はReactの初心者で、APIと連動するアプリを書こうとしています。このエラーが出続けます。

TypeError: this.setState is not a function.

を処理しようとすると、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>
        );
    }
});

解決方法は?

コールバックは別のコンテキストで行われます。 必要なのは 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 どうやら 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');