类型错误:无法读取未定义的属性“setState”

IT技术 javascript jquery ajax reactjs this
2021-01-14 03:38:24

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

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

3个回答

绑定回调函数,以便this回调内部指向 React 组件的上下文而不是回调函数

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

或者你可以使用绑定

getPosts = () =>  {
    $.ajax({
        type: 'get',
        url: urlname,
        success: function(data) {
            this.setState({ posts: data })
        }.bind(this)
    });
}
没问题,很高兴有帮助。这是大多数人都会犯的常见错误。我会建议您在将来遇到此类错误时查看绑定
2021-03-17 03:38:24

该问题与失去this 的上下文有关请试试这个:

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

或者你可以使用绑定:

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

您必须将上下文存储到一个变量中,因为“this”引用在回调中将不可用。尝试以下解决方案:

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