当this.setState()在$.get作用域中使用时,我会得到以下错误
未定义的TypeError:未定义不是函数
它在$.get作用域之外运行良好。
我怎么才能解决这个问题?
$.get(APIURL, function (data) {
this.setState({resdata: "This is a new state"});
});我不确定将jQuery AJAX替换为其他小型AJAX库的最佳实践是什么。
发布于 2014-11-27 16:32:32
可以保存对外部this的引用。
var that = this;
$.get(APIURL, function (data) {
that.setState({resdata: "This is a new state"});
});或者使用$.proxy
$.get(APIURL, $.proxy(function (data) {
this.setState({resdata: "This is a new state"});
}, this));函数内部使用的this通常指的是jqXHR对象ref http://api.jquery.com/jquery.ajax/
发布于 2016-06-17 14:41:52
您也可以使用bind(此),如React文档中所示:
https://facebook.github.io/react/tips/initial-ajax.html
下面是代码片段:
componentDidMount: function() {
this.serverRequest = $.get(this.props.source, function (result) {
var lastGist = result[0];
this.setState({
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url
});
}.bind(this));
},https://stackoverflow.com/questions/27175184
复制相似问题