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

Sha*_*did 3 javascript ajax jquery this reactjs

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

constructor(props) {
    super(props);
    this.state = { posts: [] };
    this.getPosts = this.getPosts.bind(this);
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个componentDidMount看起来像下面的方法.

componentDidMount() {
        this.getPosts();
}
Run Code Online (Sandbox Code Playgroud)

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

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

我想要设置状态,但我收到以下错误.

this.setState is not a function
Run Code Online (Sandbox Code Playgroud)

不确定是什么导致了这一点.如果有人指出我正确的方向,那将是非常有帮助的.提前致谢.

Shu*_*tri 5

绑定回调函数也是为了使this回调内部指向React Component的上下文而不是回调函数

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

或者你可以使用绑定

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