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

标签 javascript jquery ajax reactjs this

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

相关文章:

javascript - 在 HTML 元素的边框上制作 Javascript 可调整大小的处理程序

javascript - 嵌入式 Google Analytics Javascript 如何工作?

javascript - Uncaught ReferenceError : exports is not defined when importing function - TypeScript

javascript - jQuery:检查每个可见文本框的值

javascript - 静音我页面的任何声音。如何?

javascript - 跨站点 AJAX 请求

javascript - mac safari 中的 Gif 动画卡住

javascript - 重置标签的值

javascript - 选择测验数量后显示测验

jquery - fullCalendar viewRender使用ajax无限循环