我正在尝试构建一个简单的 React 应用程序。它从 ajax 调用检索数据并将其呈现到页面。问题是我让它在 ajax 调用后设置 this.props 的状态。我收到此错误:
未捕获类型错误:this.isMounted 不是函数
我一直在浏览教程并查看一些示例代码,例如在 React 站点上通过 ajax 加载信息的页面 https://facebook.github.io/react/tips/initial-ajax.html ,但我不明白是什么导致了这个错误。这是我的代码:
var ANiceReminderApp = React.createClass({
getInitialState: function(){
return {
quotes: []
};
},
componentDidMount: function(){
$.ajax({
headers: { 'X-Mashape-Key':'xxxxxx'},
url: 'https://healthruwords.p.mashape.com/v1/quotes/',
type: 'GET',
dataType: 'JSON',
success: function(data){
var quote = data[0].media;
if(this.isMounted()){
this.setState({
quotes: quote
});
}
}
});
},
render: function() {
return (
<div className="container">
hello world
<img src={this.state.quotes}/>
<button>Need more inspiration?</button>
</div>
);
}
});
React.render(<ANiceReminderApp />, document.body);
提前致谢!
最佳答案
在事件处理程序中,this
指引发事件的对象。在您的例子中,这将是 jqXHR
对象,它确实缺少 .isMounted()
方法。
要处理这种情况,您需要保留对外部 this
的引用并在事件处理程序中使用该引用,或者使用 function.bind()
强制函数保留外部上下文。
以下是如何执行后一种方法的示例:
$.ajax({
...
success: function(data) {
var quote = data[0].media;
if (this.isMounted()){
this.setState({
quotes: quote
});
}
}.bind(this); // Note the use of .bind(this) here
});
关于ajax - this.IsMounted() 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31575516/