React Router Dom v6中navigate(-1)刷新后需多次点击的问题求助
问题根源
页面刷新后,react-router维护的客户端历史栈和浏览器原生历史栈出现不同步。每次刷新都会让react-router在自己的栈中重复添加当前页面的记录,导致navigate(-1)需要多次调用才能抵消这些重复记录,回到真正的上一页。
修复方案
方案1:直接用浏览器原生返回(最简单)
放弃react-router的navigate(-1),改用浏览器自带的window.history.back(),完全基于浏览器历史栈,不受react-router内存栈的影响:
修改ProductionStatisticsUpdate组件的返回逻辑:
import { CButton } from '@coreui/react-pro'; import { useState } from 'react'; const ProductionStatisticsUpdate = () => { const [count, setCount] = useState(0); const handleCountNavigate = () => { window.history.back(); setCount(count + 1); }; return ( <> ProductionStatisticsUpdate Button press:{count} <CButton onClick={handleCountNavigate}>Redirect</CButton> </> ); }; export default ProductionStatisticsUpdate;
方案2:同步react-router历史栈(保留navigate用法)
如果必须使用react-router的navigate方法,可以在组件挂载时判断是否为刷新进入,然后替换当前历史记录,确保栈中仅存在一条当前页面的记录:
import { CButton } from '@coreui/react-pro'; import { useState, useEffect } from 'react'; import { useNavigate, useLocation } from 'react-router-dom'; const ProductionStatisticsUpdate = () => { const navigate = useNavigate(); const location = useLocation(); const [count, setCount] = useState(0); useEffect(() => { // 刷新进入时,react-router不会为location.state添加唯一key,以此作为判断依据 if (!location.state?.key) { // 替换当前历史记录,同步浏览器栈与react-router栈 navigate(location.pathname, { replace: true, state: { ...location.state, key: Date.now() } }); } }, [location, navigate]); const handleCountNavigate = () => { navigate(-1); setCount(count + 1); }; return ( <> ProductionStatisticsUpdate Button press:{count} <CButton onClick={handleCountNavigate}>Redirect</CButton> </> ); }; export default ProductionStatisticsUpdate;
方案3:直接跳转到上一页绝对路径(最稳妥)
如果明确知道上一页的路由路径,直接写死跳转路径,不依赖相对导航:
const handleCountNavigate = () => { navigate('/production-statistics'); // 直接指定上一页的路由路径 setCount(count + 1); };
内容的提问来源于stack exchange,提问作者Hiếu Nguuyễn Minh
相关产品推荐
相关产品推荐

