有没有办法知道是否有要返回的页面?
我尝试检查history.length
的值,假设任何大于1的值都意味着我们仍然可以返回(包括浏览器起始页)。但是,此解决方案不涵盖用户向前推进几页的情况:
history.length === 1
)history.length === 2
)history.length
仍为2)我还尝试设置超时,以检查几毫秒后url和查询参数是否有任何更改(这在大多数情况下适用,但不是全部),我想知道是否有更好的方法可以处理这个。
答案 0 :(得分:0)
适用于 BroswerHistory
但使用不是 officially documented 的 history.entries
成员的解决方案:
function isHistoryRoot(history) {
if (!history) return false;
if (history.length === 1) return true;
return history.location.pathname === history.entries[0].pathname;
}
const history = useHistory(); // react-router hook
const isRoot = isHistoryRoot(history);