TypeError:无法读取未定义的属性“setState” [英] TypeError: Cannot read property 'setState' of undefined

查看:1044
本文介绍了TypeError:无法读取未定义的属性“setState”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在ajax回调从REST api接收数据后设置组件的状态。这是我的组件构造函数的代码

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

然后我有 componentDidMount 看似如下的方法。

Then I have a componentDidMount method that looks like following.

componentDidMount() {
        this.getPosts();
}

现在这里是我的getPosts函数,我正在执行ajax请求。

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.

推荐答案

还绑定回调函数,以便回调内部指向React Component的上下文而不是回调函数

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

或者您可以使用绑定

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

这篇关于TypeError:无法读取未定义的属性“setState”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆