在react组件中使用jquery的ajax函数时,success:function(){}函数体内的this指向已经变成了jquery本身,而不再指向当前的react组件了。解决方法有二:
一、使用箭头函数
二、在回调函数后面使用.bind(this)来使函数内的this指向传入的this。
一、使用箭头函数
二、在回调函数后面使用.bind(this)来使函数内的this指向传入的this。
<span style="font-size:18px;">var CommentBox = React.createClass({
loadCommentsFromServer: function(){
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: (data) => {
this.setState({data: data});
},
error: function(xhr, status, err){
console.error(this.props.url, status, err.toString());
}.bind(this)
});
}
});</span>