什么是每次操作中的获取请求失败/引发错误时仅调用一次changeIsSavedStatus()的正确方法?
removeSavedDeals = () => {
this.changeIsSavedStatus();
//This Statement makes a fetch request and sets removeSelectedSavedDeals_ErrorStatus to true if error occurs
this.props.removeSelectedSavedDeals([this.props.navigation.getParam("dealDetails")._id], this.props.savedDealsListDataSource);
//This changeIsSavedStatus() statement does not gets executed as this.props.removeSelectedSavedDeals_ErrorStatus is still false when the if statement is executed.
if(this.props.removeSelectedSavedDeals_ErrorStatus){
changeIsSavedStatus();
}
}
changeIsSavedStatus=()=>{
this.setState({
isSaved:!this.state.isSaved
})
}
removeSelectedSavedDeals操作
export const removeSelectedSavedDeals = (dealIdToUnSave, dataSource) => dispatch => {
const toDelete = new Set(dealIdToUnSave);
const newDataSource = dataSource.filter(item => !toDelete.has(item._id));
//Send request to Backend to delete dealIdToUnSave from db
let url = sett.host+`/users/removeSavedDeals`;
return fetch(url, {
method: 'POST',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
dealIdToUnSave: dealIdToUnSave,
savedDealsListDataSource: newDataSource
}),
})
.then((res) => {
if (!res.ok) {
console.log("Fake Error");
throw Error(res.statusText);
}
return res;
})
.then(res => {
dispatch({
type: "removeSelectedSavedDeals_Success",
newDataSource
})
})
.catch(err => {
//TODO: Handle Error Properly
console.log("Error Encountered While Unsaving Deals: "+ err);
dispatch({
type: "removeSelectedSavedDeals_Error",
err
})
});
}
P.S。还建议是否有任何方法可以改善我的removeSavedDeals()
答案 0 :(得分:1)
如果props.removeSelectedSavedDeals
调用访存,它也应该返回一个承诺。然后,您可以{@ {1}}兑现承诺。
changeIsSavedStatus