React教程-为什么将其绑定在Ajax调用中 [英] React tutorial- why binding this in ajax call

查看:93
本文介绍了React教程-为什么将其绑定在Ajax调用中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在做React教程,想知道ajax调用中的绑定.为什么要在ajax调用中成功和错误地将其绑定?显然,当我删除绑定时,该函数将引发错误.我们使用绑定是因为函数中有this.setState并且需要正确的引用吗?

I'm doing React tutorial now, and wondering the binding in ajax call. Why do we need to bind this for success and error in the ajax call? Apparently when I removed binding, the function will throw an error. Do we use binding because we have this.setState in the function and need a right reference?

 // tutorial13.js
var CommentBox = React.createClass({
  getInitialState: function() {
    return {data: []};
  },
  componentDidMount: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  render: function() {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        <CommentList data={this.state.data} />
        <CommentForm />
      </div>
    );
  }
});

推荐答案

this引用调用该函数的对象. bind的第一个参数是this的值.因此,将function(data){...}.bind(an_object)理解为",请调用此函数,但在函数内部将this设置为引用an_object" .对于React教程,an_object是指React组件.所以:

this refers to the object that called the function. bind's first argument is the value of this. So function(data){...}.bind(an_object) can be read as "call this function, but set this inside the function to refer to an_object". In the case of the React tutorial, an_object refers to the React component. So:

 success: function(data) {
        this.setState({data: data});
 }

this引用AJAX对象. console.log(this)给我们

this refers to the AJAX object. console.log(this) gives us

Object {url: "comments.json", type: "GET", isLocal: false, global: true, processData: true…}


 success: function(data) {
        this.setState({data: data});
 }.bind(this)

this是指React组件. console.log(this)给了我们

this refers to the React component. console.log(this) gives us

ReactCompositeComponent.createClass.Constructor {props: Object, _owner: null, _lifeCycleState: "MOUNTED", _pendingCallbacks: null, _currentElement: ReactElement…}

为进一步阅读,尼古拉斯·扎卡斯(Nicholas Zakas)的书面向对象的Java脚本详细说明bind的工作原理.

For further reading, Nicholas Zakas's book Object Oriented Javascript explains in detail how bind works.

这篇关于React教程-为什么将其绑定在Ajax调用中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆