2016-03-05 89 views
0

示例来自ReactJS代码的“BIND”。我从来没有使用绑定,并不确定它在ajax调用时如何在下面的代码中执行。绑定在ajax调用上做什么?

React.createClass({ 
    componentWillMount: function() { 
     $.get(this.props.url, function (data) { 
      this.setState(data); 
     }.bind(this)); 
    }, 

    render: function() { 
     return <CommentList data={this.state.data} /> 
    } 
}); 

回答

1

它并不专指做任何ajax调用,它结合了它的使用在任何功能这个价值。
MDN

bind()方法创建新的功能,调用它时,有其 this关键字设置为所提供的值,与前面的当新功能被调用任何提供 参数给定的序列。

一个简单的例子

function doStuff() { 
    console.log(this); // would print "hello kitty" 
} 

var fn = doStuff.bind('Hello Kitty'); // set "this", then return new function 

fn(); // call with given "this" value 

在问题简单集合的代码this$.get回调函数内,在同一thiscomponentWillMount()

相关问题