gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'setState' of undefined

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:21:29 26 4
gpt4 key购买 nike

我正在尝试在 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

不太确定是什么原因造成的。如果有人指出我正确的方向,那将非常有帮助。提前致谢。

最佳答案

同时绑定(bind)回调函数,使回调中的 this 指向 React Component 的上下文,而不是回调函数

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

或者你可以像这样使用bind

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

关于javascript - 类型错误 : Cannot read property 'setState' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44257176/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com