如何等待React Router的history.goBack执行完成 无历史时跳转感谢页
解决方案
方案1:监听路由跳转完成事件执行后续逻辑
利用history实例的listen方法监听路由变化,回退操作触发路由跳转完成后,再判断是否需要跳转到感谢页:
const handleSubmit = () => { // 记录当前页面地址,用于判断回退是否生效 const currentPath = history.location.pathname; // 注册路由监听事件 const unlisten = history.listen((newLocation) => { // 路由触发变化后先销毁监听,避免重复执行 unlisten(); // 跳转后地址仍和当前地址一致,说明无历史记录可回退 if (newLocation.pathname === currentPath) { history.replace({pathname: `${url}/submit`}); } }); history.goBack(); }
该方案适配react-router v5/v6的history实例,能精准捕获回退操作的完成时机,不受异步执行逻辑影响。
方案2:提前判断历史记录长度,规避时序冲突
这是更轻量化的实现方案,无需处理异步监听逻辑,执行跳转前先判断是否有可回退的历史记录:
const handleSubmit = () => { // 常规独立页面场景下,历史记录长度大于1说明存在前置页面 if (window.history.length > 1) { history.goBack(); } else { // 无历史记录时直接跳转到感谢页 history.replace({pathname: `${url}/submit`}); } }
注意:如果页面是嵌套在iframe中,或者需要精准判断前置页面是否为同站点页面,可以在路由跳转时自定义state标记,调整判断逻辑即可。
内容的提问来源于stack exchange,提问作者Utkarsh Kumar
相关产品推荐
相关产品推荐

