【问题标题】:TypeError: Cannot read property 'setState' of undefinedTypeError:无法读取未定义的属性“setState”
【发布时间】:2017-10-30 15:06:45
【问题描述】:

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

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

【问题讨论】:

    标签: javascript jquery ajax reactjs this


    【解决方案1】:

    还要绑定回调函数,使回调中的this 指向 React 组件的上下文,而不是回调函数

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

    或者你可以使用 bind like

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

    【讨论】:

    • 没问题,很高兴能帮上忙。这是大多数人常犯的错误。我会建议您在以后遇到此类错误时检查绑定
    【解决方案2】:

    该问题与丢失 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)
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2017-05-30
        • 2021-12-09
        • 2020-07-10
        • 2019-10-10
        • 2021-07-24
        • 2022-11-17
        • 2020-09-07
        相关资源
        最近更新 更多