我有一个简单的 API 调用,用于设置列表数组的状态及其响应。我想知道如果存在错误的搜索(即像拼写错误)或者数组未使用响应设置,我将如何实现 try/catch 或错误消息。代码片段如下:
componentDidMount() {
this.search('https://itunes.apple.com/search?term=modern_baseball');
}
search(URL) {
return $.ajax({
type: 'GET',
dataType: 'json',
url: URL,
success: function (response) {
this.showResults(response);
}.bind(this),
error: function() {
alert("Error handling request");
}
});
}
showResults(response) {
console.log(response);
this.setState({
searchResults: response.results,
moveResults: []
});
}
最佳答案
尝试这样的事情:
componentDidMount() {
this.search('https://itunes.apple.com/search?term=modern_baseball');
}
search(URL) {
let self = this; //avoid the .bind call and store a ref to the current context for use inside the ajax handlers.
return $.ajax({
type: 'GET',
dataType: 'json',
url: URL,
success: function (response) {
self.showResults(response);
},
error: function() {
alert("Error handling request");
self.setState({error: "Error handling request", moveResults:[], searchResults:[]}); //set the state directly if there is an error
}
});
}
showResults(response) {
console.log(response);
this.setState({
searchResults: response.results,
moveResults: []
});
}
它将变量 (self) 设置为当前上下文 (this),然后直接在 ajax 调用的错误处理程序中调用 setState。或者,您可以定义一个回调函数,就像为成功处理程序所做的那样。
关于javascript - 根据reactjs中的条件设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45085795/