我有一个功能组件,让我们说Offers.这个组件在加载调用一个api说api_1
。 一旦收到api_1
的响应并且成功,我想触发另一个 api 调用说api_2
并根据api_2
的响应想要显示其他error screen
success screen
。另外,如果api_1
失败,我想显示error screen
const Offers =()=>{
const[api_1Success,setApi_1Success]=useState(null);
const[api_1Failure,setApi_1Failure]=useState(null);
const[api_1FetchComplete,setApi_1FetchComplete]=useState(null);
const[api_2Success,setApi_2Success]=useState(null);
const[api_2Failure,setApi_2Failure]=useState(null);
const[api_2FetchComplete,setApi_2FetchComplete]=useState(null);
const showSuccess =useCallback(() =>{
//sets some other state to render success page
},[api_2Success]);
const showError =useCallback(() =>{
//sets some other state to render error page
},[]);
const changeScreen = useCallback(() => {
if(api_2Success){
showSuccess();
} else {
showErrorScreen();
}
},[api_2Success,showSuccess,showErrorScreen]);
useEffect(()=>{ /** first useEffect **/
//dummy api call
dummyApiCall().then((response)=>{
setApi_1Success(response);
}).catch(ex=>(setApi_1Failure(ex))).finally(()=>(setApi_1FetchComplete(true)));
},[])
useEffect(()=>{ /** second useEffect **/
if(api_1FetchComplete){
if(api_1Success){
//dummy api call
dummyApiCall().then((response)=>{
setApi_2Success(response);
}).catch(ex=>(setApi_2Failure(ex))).finally(()=>(setApi_2FetchComplete(true)));
}
}
if(api_1Failure){
changeScreen();
}
},[
api_1FetchComplete,
api_1Failure,
api_1Success,
changeScreen,
])
useEffect(()=>{ /** third useEffect **/
if(api_2FetchComplete){
changeScreen();
}
},[api_2FetchComplete,changeScreen]);
return(....);
}
现在,只要api_2
的响应可用,第三次使用效果就会运行,因此更改屏幕方法会发生变化,因为它取决于api_2success
。现在,由于更改屏幕已更改,因此调用了第二个使用效果,并且循环继续。
有什么原因我可以避免在依赖数组中添加更改屏幕
创建async/await
函数有助于更好地创建和理解异步流:
useEffect(() => {
const getResponses = async () => {
try {
const response = await dummyApiCall();
setApi_1Success(response);
const response2 = await dummyApiCall();
setApi_2Success(response2);
} catch (error) {
changeScreen();
}
};
getResponses();
}, []);