【问题标题】:How to know if react-router can go back to display back button in react app如何知道react-router是否可以返回以在react app中显示后退按钮
【发布时间】:2016-09-20 00:20:15
【问题描述】:

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

我只想在用户真正可以返回时才显示返回按钮。

【问题讨论】:

    标签: reactjs react-router html5-history


    【解决方案1】:

    它给出了'POP'和'PUSH'值using this.props.location.action

    【讨论】:

    • 如果我们向后移动,它会给出“POP”动作,这样你就可以检测到它
    【解决方案2】:

    您可以通过检查 location.history 是否 > 2 来做到这一点。

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

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

    【讨论】:

    • 为什么是2
    • @EdwardSammutAlessi 如果历史长度只有 1,这意味着您尚未在堆栈中导航,因此您无法返回。仅当堆栈至少有 2 个元素时,这意味着您可以返回堆栈导航。你觉得有意义吗?
    • 这不是解决方案。假设你打开了第 1 页(history.length1),然后你转到下一页 #2(history.length2),然后再到第 3 页(history.length3 )。现在你从 #3 回到 #1,history.length 仍然是 3 但在第 #1 页你无处可退。
    • 我发现如果我打开一个新的 Chrome 标签并转到一个页面 history.length 总是 2
    • 但是如果你回去,history.length 不会减少
    【解决方案3】:

    我想我找到了解决方法

    onpopstate event

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

    我检查了它:反应路由器在状态下保存了一个关键属性: 在历史行走中,它可能包含如下数据: 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()
        }
    }
    

    【讨论】:

      【解决方案4】:

      你可以通过检查history.action来做到这一点,如果它的值是POP,那么就没有回去的路线了。这是我找到的唯一方法。

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

      【讨论】:

      • action 属性指定路由器的最后一个动作,它与历史堆栈中的剩余项无关。
      【解决方案5】:

      您可以检查loction.key,如果您有表示您在应用内路由的位置键。但是,如果您不这样做,则意味着您来自应用程序之外,或者您只是在新标签页中打开应用程序等。

      import { useHistory, useLocation } from "react-router-dom";
      const HISTORY = useHistory();
      const LOCATION = useLocation();
      
      <Button
        onClick={() => {
          if (LOCATION.key) {
            HISTORY.goBack();
          }
        }}
        disabled={!LOCATION.key}
      />;
      

      【讨论】:

        猜你喜欢
        • 2017-06-11
        • 2020-10-17
        • 2015-11-13
        • 2018-04-16
        • 2022-07-27
        • 2020-05-15
        • 2020-11-06
        • 1970-01-01
        • 2018-12-16
        相关资源
        最近更新 更多