ReactJS - 使用 jQuery 从服务器加载数据
ReactJS - Using jQuery to load data from a server
我正在从 https://facebook.github.io/react/docs/tutorial.html
学习 ReactJS
还有一个从我不太了解的服务器下载 JSON 数据的示例。
我有这个方法:
loadCommentsFromServer: 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)
});
},
可是为什么会有.bind(this)
它的目的是什么?我试图在 jQuery 文档 (http://api.jquery.com/bind/) 中查找它,但不知何故,我发现文档中显示的使用它与我如何在 React 中使用它之间没有联系。
由于 JavaScript 上的变量范围。因为你在一个函数里面,所以:
success: function(data) {
this.setState({data: data});
}
您的“this
”将引用成功函数内的范围。当你在函数后执行 .bind(this)
时,它告诉 JS 你想为此使用外部引用。在您的情况下,外部函数的作用域“loadCommentsFromServer
”
此外,我还建议您进一步阅读:
http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/
http://www.smashingmagazine.com/2014/01/23/understanding-javascript-function-prototype-bind/
绑定方法允许您更改函数的上下文。
这里有一个小例子来理解 bind()
var myPie = {
love : 'FULL'
};
function doILove(){
console.log(this.love);
}
doILove(); // returns undefined
doILove().bind(myPie); // returns 'FULL'
实际上,您的代码是调用 this.props.url
url,我们希望从服务器获取 json
数据,如果成功,我们将执行 success
函数,否则如果我们失败了,我们执行 error
函数。
我正在从 https://facebook.github.io/react/docs/tutorial.html
学习 ReactJS还有一个从我不太了解的服务器下载 JSON 数据的示例。 我有这个方法:
loadCommentsFromServer: 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)
});
},
可是为什么会有.bind(this)
它的目的是什么?我试图在 jQuery 文档 (http://api.jquery.com/bind/) 中查找它,但不知何故,我发现文档中显示的使用它与我如何在 React 中使用它之间没有联系。
由于 JavaScript 上的变量范围。因为你在一个函数里面,所以:
success: function(data) {
this.setState({data: data});
}
您的“this
”将引用成功函数内的范围。当你在函数后执行 .bind(this)
时,它告诉 JS 你想为此使用外部引用。在您的情况下,外部函数的作用域“loadCommentsFromServer
”
此外,我还建议您进一步阅读: http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/
http://www.smashingmagazine.com/2014/01/23/understanding-javascript-function-prototype-bind/
绑定方法允许您更改函数的上下文。
这里有一个小例子来理解 bind()
var myPie = {
love : 'FULL'
};
function doILove(){
console.log(this.love);
}
doILove(); // returns undefined
doILove().bind(myPie); // returns 'FULL'
实际上,您的代码是调用 this.props.url
url,我们希望从服务器获取 json
数据,如果成功,我们将执行 success
函数,否则如果我们失败了,我们执行 error
函数。