反应路由器检查是否可以返回

时间:2020-06-26 15:03:05

标签: reactjs react-router

有没有办法知道是否有要返回的页面?

我尝试检查history.length的值,假设任何大于1的值都意味着我们仍然可以返回(包括浏览器起始页)。但是,此解决方案不涵盖用户向前推进几页的情况:

  • 打开第一页(history.length === 1
  • 转到下一页(history.length === 2
  • 返回一页(history.length仍为2)

我还尝试设置超时,以检查几毫秒后url和查询参数是否有任何更改(这在大多数情况下适用,但不是全部),我想知道是否有更好的方法可以处理这个。

1 个答案:

答案 0 :(得分:0)

适用于 BroswerHistory 但使用不是 officially documentedhistory.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);