且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

TypeError:无法读取未定义的属性“setState”

更新时间:2022-06-10 21:57:41

还绑定回调函数,以便回调内部指向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)
    });
}