我正在尝试在 ajax 回调从 REST api 接收数据后设置组件的状态。这是我的组件构造函数代码
constructor(props) {
super(props);
this.state = { posts: [] };
this.getPosts = this.getPosts.bind(this);
}
然后我有一个componentDidMount看起来像下面的方法。
componentDidMount() {
this.getPosts();
}
现在这是我在执行 ajax 请求的 getPosts 函数。
getPosts = () => {
$.ajax({
type: 'get',
url: urlname,
success: function(data) {
this.setState( { posts: data } )
}
});
}
我想设置状态,但出现以下错误。
this.setState is not a function
不太确定是什么原因造成的。如果有人指出我正确的方向,那将非常有帮助。提前致谢。