React의 새로운 기능이며 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>
        );
    }
});
답변
콜백은 다른 상황에서 이루어집니다. 당신은 필요 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');
답변
ES6 화살표 기능으로 .bind (this)가 필요하지 않습니다.
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);
        }
    });
답변
메소드 this를 호출하기 전에 참조를 저장할 수도 있습니다 api.
componentDidMount:function(){
    var that = this;
    VK.init(function(){
        console.info("API initialisation successful");
        VK.api('users.get',{fields: 'photo_50'},function(data){
            if(data.response){
                that.setState({ //the error happens here
                    FirstName: data.response[0].first_name
                });
                console.info(that.state.FirstName);
            }
        });
    }, function(){
        console.info("API initialisation failed");
    }, '5.34');
},
답변
React는 class이것을 self 대신 대신 사용해야하는 모든 메소드에서 이것을 바인딩하는 것이 좋습니다 function.
constructor(props) {
    super(props)
    this.onClick = this.onClick.bind(this)
}
 onClick () {
     this.setState({...})
 }
또는 arrow function대신 사용할 수 있습니다 .
답변
당신은 당신의 이벤트를 바인딩해야합니다
예를 들어
// place this code to your constructor
this._handleDelete = this._handleDelete.bind(this);
// and your setState function will work perfectly
_handleDelete(id){
    this.state.list.splice(id, 1);
    this.setState({ list: this.state.list });
    // this.setState({list: list});
}
답변
이제 ES6에는 화살표 기능이 있습니다. 바인드 (this) 표현식과 혼동하면 화살표 기능을 시도 할 수 있습니다.
이것이 내가하는 방법입니다.
componentWillMount() {
        ListApi.getList()
            .then(JsonList => this.setState({ List: JsonList }));
    }
 //Above method equalent to this...
     componentWillMount() {
         ListApi.getList()
             .then(function (JsonList) {
                 this.setState({ List: JsonList });
             }.bind(this));
 }
답변
화살표 함수를 사용하는 경우 이것을 로컬 변수에 할당 할 필요가 없습니다. 화살표 기능은 자동으로 바인딩되며 범위 관련 문제를 피할 수 있습니다.
아래 코드는 다른 시나리오에서 화살표 기능을 사용하는 방법을 설명합니다
componentDidMount = () => {
    VK.init(() => {
        console.info("API initialisation successful");
        VK.api('users.get',{fields: 'photo_50'},(data) => {
            if(data.response){
                that.setState({ //this available here and you can do setState
                    FirstName: data.response[0].first_name
                });
                console.info(that.state.FirstName);
            }
        });
    }, () => {
        console.info("API initialisation failed");
    }, '5.34');
 },
