我正在尝试构建一个简单的React应用程序。它从ajax调用中检索数据并将其呈现到页面。问题是我让它设定了这个的状态。ajax调用后的Props。我收到这个错误:
Uncaught TypeError: this.isMounted is not a function
我一直在通过教程和查看一些示例代码,就像这个页面上通过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
});
@gilly3的回答解释了这个问题。然而,我更喜欢另一种解决方案:React将有效地自动绑定类方法,这意味着this
将正确地引用实例。所以我通常使用方法作为回调:
React.createClass({
componentDidMount: function(){
$.ajax({
// the method is already bound to the component
success: this.onDataReceived
});
},
onDataReceived: function(data) {
var quote = data[0].media;
if(this.isMounted()){
this.setState({
quotes: quote
});
}
},
// ...
});
这有两个优点:
至少在理论上,React的绑定比使用
.bind
更有效。如果您必须多次调用.bind
,则尤其如此。它使调用回调逻辑更容易通过一些其他代码路径(例如,如果你也想接受通过
props
提供的数据)。
这个讨论也值得一看,它表明isMounted
将来可能会被弃用——在这种情况下,建议的路径是保存对AJAX请求的引用,并在componentWillUnmount
上中止它。