TypeError: Cannot read property 'setState' of undefined

蓝咒 提交于 2019-11-26 03:45:42

问题


I am trying to setState of a component after a ajax callback receives data from REST api. here\'s my code for the component constructor

constructor(props) {
    super(props);
    this.state = { posts: [] };
    this.getPosts = this.getPosts.bind(this);
}

Then I have a componentDidMount method that looks like following.

componentDidMount() {
        this.getPosts();
}

Now here\'s my getPosts function where I am doing the ajax request.

getPosts = () =>  {
    $.ajax({
        type: \'get\',
        url: urlname,
        success: function(data) {
            this.setState( { posts: data } )
        }
    });
}

I am tying to set the State but I am getting the following error.

this.setState is not a function

Not really sure what is causing this. It would be really helpful if someone points me to the right direction. Thanks in advance.


回答1:


Bind the callback function also so that this inside the callback points to the context of the React Component and not the callback function

getPosts = () =>  {
    $.ajax({
        type: 'get',
        url: urlname,
        success: (data) => {
            this.setState( { posts: data } )
        }
    });
}

or you could use bind like

getPosts = () =>  {
    $.ajax({
        type: 'get',
        url: urlname,
        success: function(data) {
            this.setState({ posts: data })
        }.bind(this)
    });
}



回答2:


The issue is related with loosing context of this. Please try this:

let self = this;
getPosts = () =>  {
    $.ajax({
        type: 'get',
        url: urlname,
        success: function(data) {
            self.setState( { posts: data } )
        }
    });
}

or you can use bind:

getPosts = () =>  {
        $.ajax({
            type: 'get',
            url: urlname,
            success: function(data) {
                self.setState( { posts: data } )
            }
        });
    }.bind(this)



回答3:


You have to store the context into a variable as "this" reference will not be available in the callback. Try below solution:

getPosts = () =>  {
let that=this;
    $.ajax({
        type: 'get',
        url: urlname,
        success: function(data) {
            that.setState( { posts: data } )
        }
    });
}


来源:https://stackoverflow.com/questions/44257176/typeerror-cannot-read-property-setstate-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!