2016-03-05 91 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()

相關問題