TypeError: Cannot read property #39;setState#39; of undefined(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();
}
现在这是我正在执行 ajax 请求的 getPosts 函数.
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.
推荐答案
还要绑定回调函数,让回调中的 this
指向 React 组件的上下文而不是回调函数
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 } )
}
});
}
或者你可以使用 bind like
or you could use bind like
getPosts = () => {
$.ajax({
type: 'get',
url: urlname,
success: function(data) {
this.setState({ posts: data })
}.bind(this)
});
}
这篇关于TypeError:无法读取未定义的属性“setState"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:TypeError:无法读取未定义的属性“setState"


- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01