javascript - React.js,在 useEffect 挂钩中,window.location.href 不会停止中断进一步的代码执行
问题描述
最近我发现,如果我使用window.location.href
重定向,并且我没有指定return {}
,进一步的代码将继续执行,这不是我想要的。
如果这与以下内容有关,我可以要求澄清一下:
- React.js
useEffect
钩子。 window.location.href
默认情况下重定向后不会中断。- 异步等待。
useEffect(() => {
const myFunction = () =>
ajax({
url: API_ROUTES.MY_EXAMPLE_ROUTE,
requestBody: {
request_message: "Hi, pls help!",
},
handleSuccess: response => {
if (condition === true)) {
window.location.href = "http://google.com";
// If I do not put return here, code will continue to execute.
return {};
}
// Code that I do not want to run after redirection
history.push(routes.error);
return {};
},
handleError: error => {
history.push(routes.error);
},
});
const init = async () => {
await myFunction();
};
init();
}, []);
解决方案
您似乎希望代码在将 设置window.location.href
为一个值后停止执行该函数,但这是不正确的。要过早退出函数,您确实需要使用return
.
更好的解决方案是使用else
条件,以便history.push
仅在condition
为假时运行。
if (condition) {
window.location.href = 'http://www.google.com';
} else {
history.push(routes.error);
}
推荐阅读
- android - 后台运行
- ios - 队列何时会认为任务已完成?
- css - 使用 flex 分割面板
- angular - 角度控制匹配未知
- jquery - 如果页面未加载,ajaxForm 将重定向到响应
- asp.net-core - .NetCore - 使用 MultipleViews/BindPperty 进行模型绑定
- javascript - 对 props 块组件中的本机回调函数做出反应以重新渲染
- sql-server - 在 MS Access 中使用通用 SQL 日期格式的方法是什么?
- r - For循环获取日期范围R
- wordpress - Wordpress,基于 url 请求的动态 404.php 标题