React - FC -如何在React环境中停止执行



目前我有一个React + Redux应用程序。我想在任何API调用失败时停止执行。我使用axios调用API。我试图通过在axios拦截器中抛出错误来停止执行。

axiosInstance.interceptors.response.use(
(response: AxiosResponse) => response,
async (failedRequest: iFailedRequest) =>
apiErrorHandler(failedRequest)
);

这是我的apiErrorHanlder方法。

const apiErrorHandler(failedRequest) = () => {
throw new Error("error") // I want my application execution to stop here without affecting the UI state
}

但问题是,在react/JS的执行继续进行到下一行代码。

const MyComponent = ()  => {
const apiCall = async () => {
await axios.get("/api_end_point") // Stop execution here if API call has been failed
console.log("success API call") // This should only be printed in case of successful API call
}
useEffect(() => {
apiCall();
}, [])
return <></>;
}

可以使用try/catch块:

文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch

try {
await axios.get("/api_end_point")
} catch (error) {
console.error(error);
}

相关内容

  • 没有找到相关文章

最新更新