React 教程 - 为什么在 ajax 调用中绑定它

React tutorial- why binding this in ajax call

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

 // 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" 指的是 ReactClass.createClass.Constructor。所以在 ajax 调用成功和错误中绑定它的原因是确保我们在调用 this.setState({data:data});console.error(this.props.url, status, err.toString());

时拥有正确的 "this"

如果我们不绑定 "this"。我们失去了正确的 React "this",并且 "this" 随时可能变成 window、jQuery 或其他东西。这就是我们得到 "Uncaught TypeError: undefined is not a function" 错误的原因。

this指调用函数的对象。 bind 的第一个参数是 this 的值。所以function(data){...}.bind(an_object)可以读作"call this function, but set this inside the function to refer to an_object"。在 React 教程中,an_object 指的是 React 组件。所以:

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

this 指的是 AJAX 对象。 console.log(this) 给我们

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) 给我们

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

如需进一步阅读,Nicholas Zakas 的书 Object Oriented Javascript 详细解释了 bind 的工作原理。

该语句等同于

componentDidMount: function() {
    var me = this;

    $.ajax({
      url: this.props.url,
      dataType: 'json',
      success: function(data) {
        me.setState({data: data});
      }
    });
}