h5實(shí)現(xiàn)列表頁(yè)點(diǎn)擊進(jìn)入詳情頁(yè),返回時(shí)還停留在列表頁(yè)之前的位置不刷新
- 詳情頁(yè)作為一個(gè)組件的形式,引入列表頁(yè)。
- 列表頁(yè)卡片點(diǎn)擊的時(shí)候,推入一個(gè)假的history
// 推入新的歷史狀態(tài),實(shí)現(xiàn)假的"路由跳轉(zhuǎn)"效果
window.history.pushState({ from: 'detail' }, '', window.location.href);
- 監(jiān)聽瀏覽器返回按鈕
// 監(jiān)聽瀏覽器返回事件,實(shí)現(xiàn)假的"路由跳轉(zhuǎn)"效果
useEffect(() => {
const handlePopState = (event: PopStateEvent) => {
// 如果彈窗是打開的,則關(guān)閉彈窗
if (selected) {
console.log('檢測(cè)到返回操作,關(guān)閉用戶詳情彈窗');
setSelected(null);
// 阻止默認(rèn)的返回行為,保持當(dāng)前頁(yè)面狀態(tài)
event.preventDefault();
// 重新推入當(dāng)前狀態(tài),確保URL不變
window.history.replaceState(null, '', location.pathname + location.search);
}
};
// 監(jiān)聽 popstate 事件
window.addEventListener('popstate', handlePopState);
// 清理事件監(jiān)聽器
return () => {
window.removeEventListener('popstate', handlePopState);
};
}, [selected]);//顯示詳情頁(yè)時(shí),需要監(jiān)聽的值