我现在正在做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>
);
}
});
Run Code Online (Sandbox Code Playgroud)
Kei*_*ong 12
this是指调用函数的对象.bind第一个论点是价值this.因此function(data){...}.bind(an_object)可以读作"调用此函数,但this在函数内部设置引用an_object".在React教程的情况下,an_object引用React组件.所以:
success: function(data) {
this.setState({data: data});
}
Run Code Online (Sandbox Code Playgroud)
this指的是AJAX对象.console.log(this)给我们
Object {url: "comments.json", type: "GET", isLocal: false, global: true, processData: true…}
Run Code Online (Sandbox Code Playgroud)
success: function(data) {
this.setState({data: data});
}.bind(this)
Run Code Online (Sandbox Code Playgroud)
this指React组件.console.log(this)给我们
ReactCompositeComponent.createClass.Constructor {props: Object, _owner: null, _lifeCycleState: "MOUNTED", _pendingCallbacks: null, _currentElement: ReactElement…}
Run Code Online (Sandbox Code Playgroud)
为了进一步阅读,Nicholas Zakas的书" 面向对象的Javascript"详细解释了如何bind工作.
该语句相当于
componentDidMount: function() {
var me = this;
$.ajax({
url: this.props.url,
dataType: 'json',
success: function(data) {
me.setState({data: data});
}
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4706 次 |
| 最近记录: |