Shio Y. Blog

如何保证同域名下的 router 后退操作

在做自己的 Side Project 需要每个页面添加类似于 native app 的后退按钮,返回到之前已访问的页面。

导航栏截图

因为使用了 react-router,自然的想法是使用history.goBack()


_10
import { useHistory } from 'react-router-dom';
_10
_10
const App = () => {
_10
const history = useHistoy();
_10
_10
return (
_10
<button onClick={() => history.goBack()}
_10
)
_10
}

Easy!但是在浏览器中这样的问题是:如果用户是从别的页面(比如 google.com)通过链接点击或者地址栏输入我们的页面地址的,此时当点击后退按钮,用户会回到 google.com,这显然不是一个 SPA 多期望的。我们希望用户始终处于我们的 web app 中。

Stackoverflow上的答案并不能解决这一问题,直到我找到这个issue。我们可以通过判断 locationkey 是否有值来判断当前页面是否是我们 app 的初始页面。


_14
import { useHistory, useLocation } from 'react-router-dom';
_14
_14
const App = () => {
_14
const history = useHistory();
_14
const location = useLocation();
_14
_14
// go back to the previous page
_14
// fallback to home page if we are on the initial page
_14
const goBack = () => (location.key ? history.goBack() : history.push('/'));
_14
_14
return (
_14
<button onClick={() => history.goBack()}
_14
)
_14
}

写于 2021年06月26日