React Router 5+ HashRouter Handle Browser Back button



我无法处理浏览器返回按钮。我想做的是提醒用户,如果他们返回,他们将被带到主屏幕,必须重新启动他们所在的流。我使用的是HashRouter,React Router v.2.0。我尝试了以下操作,但不起作用

import { useHistory } from 'react-router-dom'

const [ locationKeys, setLocationKeys ] = useState([])
const history = useHistory()
useEffect(() => {
return history.listen(location => {
if (history.action === 'PUSH') {
setLocationKeys([ location.key ])
}
if (history.action === 'POP') {
if (locationKeys[1] === location.key) {
setLocationKeys(([ _, ...keys ]) => keys)
// Handle forward event
} else {
setLocationKeys((keys) => [ location.key, ...keys ])
// Handle back event
}
}
})
}, [ locationKeys, ])

从文档中编辑,HashRouter不支持location.key,因此上面的代码片段应该不起作用。https://reactrouter.com/web/api/HashRouter

我还尝试了下面的方法,这会产生不希望的行为。根据历史堆栈上的内容,确认会被调用两次。我还注意到,在用户确认或取消之前,浏览器url更改为以前的屏幕url,这似乎导致了这种奇怪的行为。

const listener = function (event) {
console.log('back');
if (confirm('are you sure?')) {
console.log("go back to home";
} else {
console.log("stay")
}
};
useEffect(() => {
window.addEventListener('popstate', listener, false);
return () => {
console.log('removing listener');
window.removeEventListener('popstate', listener, false);
};
}, []);

您可以尝试历史对象的块方法

history.block(() => {
/// your code           
});

最新更新