我试图让fetch停止并在它返回errorMessage时发出警报,
所以()=>this.toggleModal()
不会被执行。
handleSubmit(event){
const url = 'http://localhost:8000/issue/';
var issueid = 13900;
var issueid = document.getElementById("SearchTxt").value;
if(issueid == 0){
alert('Please insert IssueID or IssueKey')
}else{
var string2 = url+issueid;
fetch(string2)
.then(function(response) {
return response.json();
})
.then((myJson) => this.setState({example: myJson},() => this.toggleModal()))
}
}
当问题不存在时返回JSON:
{
errorMessages: [
"Issue Does Not Exist"
],
errors: { },
}
答案 0 :(得分:1)
如果您想取消return response.json();
的执行,可以执行以下操作
handleSubmit(event){
const url = 'http://localhost:8000/issue/';
var issueid = document.getElementById("SearchTxt").value;
if(issueid == 0 || issueid == "" || issueid == undefined || issueid == null){
alert('Please insert IssueID or IssueKey')
return;
}
var string2 = url+issueid;
fetch(string2)
.then(function(response) {
const oJson = response.json();
// your validation of the json
if(oJson.hasOwnProperty("errorMessages") && oJson.errorMessages.includes("Issue Does Not Exist")
return Promise.reject(oJson.errorMessages[0]); // maybe use a better way instead of this hardcoded index
// set state if everything was properly done
this.setState({example: myJson},() => this.toggleModal())
})
.catch(error => {
// do some alert stuff
alert(error);
});
}
答案 1 :(得分:0)
我设法解决了这个问题:
handleSubmit(event){
const url = 'http://localhost:8000/issue/';
var issueid = 13900;
var issueid = document.getElementById("SearchTxt").value;
if(issueid == 0){
alert('Please insert IssueID or IssueKey')
}else{
var string2 = url+issueid;
fetch(string2)
.then(function(response) {
return response.json();
})
.then((myJson) => this.conditionalChaining(myJson));
}
}
conditionalChaining(myJson) {
if (myJson.errorMessages == 'Issue Does Not Exist') {
alert('Issue doesn´t exist')
} else {
this.setState({example: myJson},() => this.toggleModal());
}
}