【问题标题】:purpose of .bind(this) at end of ajax callback?.bind(this) 在 ajax 回调结束时的目的?
【发布时间】:2014-08-08 18:01:11
【问题描述】:

从 reactjs 教程中,在 ajax 回调末尾添加 .bind(this) 的目的是什么?没有它,代码能正常工作吗?

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

【问题讨论】:

  • 类似here。如果没有.bind(this)this 引用在自定义函数(在 reactJs 组件中定义)中使用时变为 null。

标签: ajax reactjs


【解决方案1】:

在 ajax 回调末尾添加 .bind(this) 的目的是让 this 与您的反应类相关。换句话说,您可以添加:

var self = this;

在 ajax 之外,它的工作原理是一样的。 你的代码等于:

var self = this;
$.ajax({
    .
    .
    data: JSON.stringify({text: text}),
    success: function (data) {
        self.setState({data: data});
    },
    .
    .
});

【讨论】:

    【解决方案2】:

    它确保this 将是回调中的正确对象。见Function.prototype.bind()

    特定于 react 的替代方法是:

    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 在回调中。

    【讨论】:

    猜你喜欢
    • 2016-05-10
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 2016-09-21
    • 1970-01-01
    相关资源
    最近更新 更多