如何知道 react-router 是否可以返回以在 react app 中显示后退按钮

问题描述 投票:0回答:5

似乎没有 API 方法来检测您是否可以从应用程序的当前页面返回。可以检查历史长度,但这包括前向和后向堆栈。

我只想在用户实际可以返回时显示后退按钮。

reactjs react-router html5-history
5个回答
14
投票

您可以检查

location.key
是否有位置密钥,这意味着您在应用程序内进行了路由。但是,如果您不这样做,则意味着您来自应用程序外部,或者您只是在新标签页中打开应用程序等。

import { useHistory, useLocation } from "react-router-dom";
const history = useHistory();
const location = useLocation();

<Button
  onClick={() => {
    if (location.key) {
      history.goBack();
    }
  }}
  disabled={!location.key}
/>;

对于 V6 和更新版本:

import { useHistory, useLocation } from "react-router-dom";
const history = useHistory();
const location = useLocation();

<Button
  onClick={() => {
    if (location.key !== 'default') {
      history.goBack();
    }
  }}
  disabled={location.key === 'default'}
/>;

11
投票

如果它的值为

history.action
,您可以通过检查
POP
来完成,那么就没有返回的路线。这是我找到的唯一方法。

<Button
  onClick={() => {
    if (history.action !== 'POP') history.goBack();
  }}
  disabled={history.action === 'POP'}
/>

3
投票

我想我找到了解决方法

onpopstate事件

调用 history.pushState() 或 history.replaceState() 不会触发 popstate 事件。 popstate 事件仅通过执行浏览器操作 触发,例如在同一文档的两个历史条目之间导航时单击后退按钮(或在 JavaScript 中调用 history.back())。

我检查了一下:react router saves at state a key property: 在历史行走中,它可能包含如下数据: event.state: {key: "jr2go2", state: undefined}

当我们返回到我们进入网站或应用程序的最后一页时,此状态属性将为空: event.state: null ,

所以我们可以用 redux + rxjs(例如)这样处理它:

// epic
export const handleHistoryWalkEpic = () =>
  fromEvent<PopStateEvent>(window, 'popstate')
  .pipe(
    map(event => setCanGoBack(!!event.state)),
  )

// reducer
case NavigationBarActionsTypes.SET_CAN_GO_BACK:
  return {
    ...state,
    canGoBack: action.payload.canGoBack,
  }

并且您应该在任何推送历史记录操作上将 canGoBack 设置为 true,您可以使用任何路由器处理程序组件:

componentWillUpdate(nextProps: any) {
    let { location } = this.props;

    if (nextProps.history.action === 'PUSH') {
      this.props.setCanGoBack()
    }
}

-2
投票

您可以通过检查

location.history
是否 > 2 来做到这一点。

在您的应用程序中显示或不显示后退按钮的示例:

onBack={ history.length > 2 ? () => { history.goBack() } : null }

-4
投票

它给出“POP”和“PUSH”值

using this.props.location.action

© www.soinside.com 2019 - 2024. All rights reserved.