为了账号安全,请及时绑定邮箱和手机立即绑定

TypeError:无法读取未定义的属性“ setState”

TypeError:无法读取未定义的属性“ setState”

桃花长相依 2019-11-20 14:39:27
我试图在ajax回调从REST api接收数据后设置组件的setState。这是我的组件构造函数代码constructor(props) {    super(props);    this.state = { posts: [] };    this.getPosts = this.getPosts.bind(this);}然后,我有一个componentDidMount如下所示的方法。componentDidMount() {        this.getPosts();}现在,这是我执行getAJAX请求的getPosts函数。getPosts = () =>  {    $.ajax({        type: 'get',        url: urlname,        success: function(data) {            this.setState( { posts: data } )        }    });}我想设置状态,但出现以下错误。this.setState is not a function不太清楚是什么原因造成的。如果有人指出我正确的方向,那将非常有帮助。提前致谢。
查看完整描述

3 回答

?
繁星淼淼

TA贡献1775条经验 获得超11个赞

还绑定回调函数,以便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)

    });

}


查看完整回答
反对 回复 2019-11-20
?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

这个问题与失去的环境相关的这个。请尝试以下方法:


let self = this;

getPosts = () =>  {

    $.ajax({

        type: 'get',

        url: urlname,

        success: function(data) {

            self.setState( { posts: data } )

        }

    });

}

或者您可以使用bind:


getPosts = () =>  {

        $.ajax({

            type: 'get',

            url: urlname,

            success: function(data) {

                self.setState( { posts: data } )

            }

        });

    }.bind(this)


查看完整回答
反对 回复 2019-11-20
?
慕姐8265434

TA贡献1813条经验 获得超2个赞

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


getPosts = () =>  {

let that=this;

    $.ajax({

        type: 'get',

        url: urlname,

        success: function(data) {

            that.setState( { posts: data } )

        }

    });

}

分享编辑


查看完整回答
反对 回复 2019-11-20
  • 3 回答
  • 0 关注
  • 1013 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信