我使用三元 if else 来调用不同的 API(API 调用存储在另一个文件中)。
(this.props.item === "burger" ? burgerObj.GetBurger (this.props.burger_id) : pizzaObj.GetPizza (this.props.pizza_id)) // burgerObj and pizzaObj are objects of their respective classes
.then((response) => {
if(response.status === 400) {
console.log ("Bad Request")
}
else {
response.json()
.then((findresponse) => {
this.prepareFood(findresponse) // Some function call
})
}
})
.catch ((e) => {
console.log (e)
})
}
// API calls in different classes. Same is for GetPizza
GetBurger(burger_id) {
return fetch(url + 'burgerId' + burger_id , {
headers: {
'Authorization': 'Bearer ' + authorization,
'Content-Type': 'application/json',
}
})
}
这是处理此类调用的错误方式吗?因为当我使用此 API 时,调用工作正常,但代码永远不会达到 promise (.then((response) => { - 第 2 行)。如果我检查网络,我可以看到从 API 返回的响应。抱歉,如果我对 React 还很陌生,有些地方错了。请帮助我。
最佳答案
使用三元就可以了。但是您可以使用 Async/Await
来清理回调 -
const { item, burger_id, pizza_id} = this.props;
function fetchWrapper(url) {
fetch(url, {
headers: {
Authorization: `Bearer${authorization}`,
'Content-Type': 'application/json',
}
})
.then(data => { return { data, error: null }; })
.catch(error => { return { error, data: null }; });
}
// API calls in different classes. Same is for GetPizza
async function GetBurgerAsync(burgerId) {
let response = await fetchWrapper(`url burgerId${burgerId}`);
const data = await response.json();
return data;
}
const foodType = item === 'burger' ? GetBurgerAsync(burger_id) : GetPizzaAsync(pizza_id);
if (foodType.data) {
this.prepareFood(foodType);
}
编辑:重构,将 fetch
包装为每次调用时只有 url 应该更改。所有调用中的 token 都应该相同。
关于javascript - 在 React 中使用三元 if else 和 Promise 是一个不好的方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55529624/