.bind(this)在ajax回调结束时的目的?

 媣栺葒尘_383 发布于 2023-01-08 17:22

在reactjs教程中,.bind(this)在ajax回调结束时有什么目的?没有它,代码是否正常工作?

        data: JSON.stringify({text: text}),
        success: function (data) {
            this.setState({data: data});
        }.bind(this),

Brigand.. 57

它确保this它将成为回调中的正确对象.请参见Function.prototype.bind().

反应的另一个具体方法是:

myAjaxFunction: function(){
  $.getJSON('/something', this.handleData);
},
handleData: function(data){
  this.setState({data: data});
}

这是有效的,因为React为您处理组件方法的绑定.

如果您在没有绑定的情况下运行原始代码,则会收到此错误:TypeError: undefined is not a function因为this === window在回调中;

或者在严格模式下:TypeError: Cannot read property 'setState' of undefined,this === undefined在回调中的位置.

1 个回答
  • 它确保this它将成为回调中的正确对象.请参见Function.prototype.bind().

    反应的另一个具体方法是:

    myAjaxFunction: function(){
      $.getJSON('/something', this.handleData);
    },
    handleData: function(data){
      this.setState({data: data});
    }
    

    这是有效的,因为React为您处理组件方法的绑定.

    如果您在没有绑定的情况下运行原始代码,则会收到此错误:TypeError: undefined is not a function因为this === window在回调中;

    或者在严格模式下:TypeError: Cannot read property 'setState' of undefined,this === undefined在回调中的位置.

    2023-01-08 17:23 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有