【问题标题】:disable back button in react-router 2禁用反应路由器2中的后退按钮
【发布时间】:2016-07-08 13:51:45
【问题描述】:

我正在使用 react-router 2。我的路由定义为

   <Route path="/" component={App}>
       <IndexRoute component={Home}/>
       <Route path="/about" component={About}/>
       <Route path="/login" component={Login} onEnter={redirectToDashboard}/>
       <Route path="/logout" component={Logout} onEnter={logoutSession}/>
       <Route path="/dashboard" component={Dashboard} onEnter={redirectToLogin}/>
   </Route>

一切正常,但我无法从仪表板页面禁用后退按钮。

成功登录后,我将用户重定向到仪表板页面,但是当用户单击返回按钮时,它再次进入登录页面。当用户在仪表板页面上时,我想禁用browser 的后退按钮。

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    您最好的选择是,当用户登录时,他/她会被重定向到仪表板。如果由于某种原因用户点击后退按钮,您应该:

    如果用户已登录 留在页面仪表板上

    if(logged) {
      history.pushState(null, null, location.href);
      window.onpopstate = function(event) {
        history.go(1);
      };
    }
    

    无法返回。

    【讨论】:

    • 目前,这会禁用所有路线的后退按钮。例如,当我从仪表板路由到另一个页面并单击后退按钮时,如何让后退按钮工作?如何使用返回按钮返回仪表板?
    【解决方案2】:

    应用所有这些技巧后,URL 会暂时更改为 login,然后更改为 wherever-we-push。 相反,我们可以做的是:在登录中,api端点返回成功,做:

    history.replace('/Whatever_screen')
    

    这将从window.history堆栈中删除登录屏幕,并且屏幕不会闪烁。

    【讨论】:

    • 您能否更好地格式化您的答案并尝试重新排列它?
    • 这应该被接受为正确答案。
    【解决方案3】:

    无法禁用浏览器按钮。 我的建议是,如果他/她已登录,则将用户重定向回仪表板页面

    【讨论】:

      【解决方案4】:

      在您要禁用的页面上(例如,在 LoginApp 上)添加此块,以禁用网络历史记录

      componentDidMount() {
          window.history.pushState(null, document.title, window.location.href);
          window.addEventListener('popstate', function (event){
              window.history.pushState(null, document.title,  window.location.href);
          });
      }
      

      【讨论】:

        【解决方案5】:

        实际上你不能禁用返回按钮。您可以通过阻止浏览器的“返回”操作来使用 hack。只需在您的Dashboard 组件compnentWillMount() 生命周期方法中添加一些将触发浏览器“forward”操作的代码:

        componentWillMount() {
           setTimeout(() => {
             window.history.forward()
           }, 0)
           window.onunload=function(){null};
        }
        

        但很可能更好的解决方案是根据用户登录状态进行一些重定向。

        【讨论】:

          【解决方案6】:

          在您的登录屏幕中添加替换到 /dashboard

          import React, { Component } from 'react';
          import { withRouter } from 'react-router-dom'
          import createBrowserHistory from 'history/createBrowserHistory'
          const history = createBrowserHistory()
          
          class LoginPage extends Component {
              componentDidMount(){
                  history.replace({ pathname: '/dashboard' })
              }
              render() {
                  const { history } = this.props
                  return (
                      <div>
                      <h1>Login Page</h1>
                      <button onClick={() => {
                        login().then(() => {
                          history.push('/dashboard')
                        })
                      }}>Login</button>
                    </div>
                  );
              }
          }
          
          export default withRouter(LoginPage);
          

          原因是将您当前的路径 (/login) 替换为 /dashboard。在添加之前,请确保您正确设置了身份验证。

          【讨论】:

          • 这是最好的答案。 history.replace(...) 用新视图替换当前视图,点击后退按钮可以返回之前的视图。 History Doc
          【解决方案7】:

          为了提高代码的可重用性,我们可以在index.html 中添加一个事件监听器,并从我们所有的componentDidMount() 方法中调度浏览器返回禁用事件。

          在index.html,

          window.addEventListener('navigationhandler', function (e) {
            window.history.pushState(null, document.title, window.location.href);
            window.addEventListener('popstate', function (event) {
              window.history.pushState(null, document.title, window.location.href);
            });
          });
          

          在 React componentDidMount() 方法中,

          componentDidMount() {
             window.dispatchEvent(new CustomEvent("navigationhandler"));
          }
          

          【讨论】:

          • 目前,这会禁用所有路线的后退按钮。例如,当我从仪表板路由到另一个页面并单击后退按钮时,如何让后退按钮工作?如何使用返回按钮返回仪表板?
          • 您可以手动处理后退按钮或获取当前页面的状态并在用户尝试返回时存储到变量尝试检查值并相应地继续,否则如果您想覆盖当前返回按钮功能,不要调用window.dispatchevent方法,可以写push state方法
          • 如果您能将示例复制到 codepen 或沙箱,我将不胜感激。谢谢。
          • 当然,我会为您提供样本。
          • 你能问个问题并在那儿标记我,这样我就可以回答社区也可以使用它
          【解决方案8】:

          无法禁用浏览器按钮。但是我们可以使用listen()、go() 和push() 等历史方法来覆盖react.js 中后退按钮的默认行为。也尝试使用withRouter()。

          以下是执行此操作的示例代码。请查看componentDidMount() 和componenetDidUnmount() 方法。

          import React from "react";
          import { Redirect, Switch, Route, withRouter } from "react-router";
          
          import Page1 from "./Page1";
          import Page2 from "./Page2";
          import Page3 from "./Page3";
          
          class App extends React.Component {
            constructor(props) {
              super(props);
          
              // Store the previous pathname and search strings
              this.currentPathname = null;
              this.currentSearch = null;
            }
          
            componentDidMount() {
              const { history } = this.props;
          
              history.listen((newLocation, action) => {
                if (action === "PUSH") {
                  if (
                    newLocation.pathname !== this.currentPathname ||
                    newLocation.search !== this.currentSearch
                  ) {
                    this.currentPathname = newLocation.pathname;
                    this.currentSearch = newLocation.search;
          
                    history.push({
                      pathname: newLocation.pathname,
                      search: newLocation.search
                    });
                  }
                } else {
                  history.go(1);
                }
              });
            }
          
            componentWillUnmount() {
              window.onpopstate = null;
            }
          
            render() {
              return (
                <Switch>
                  <Route exact path="/" render={() => <Redirect to="/page1" />} />
                  <Route path="/page1" component={Page1} />
                  <Route path="/page2" component={Page2} />
                  <Route path="/page3" component={Page3} />
                </Switch>
              );
            }
          }
          
          export default withRouter(App);
          

          更多:Disable react back button

          【讨论】:

            猜你喜欢
            • 2020-10-29
            • 2017-03-08
            • 2017-08-07
            • 2020-07-18
            • 2020-04-22
            • 2019-03-15
            • 2021-08-25
            • 2021-10-27
            • 2022-08-20
            相关资源
            最近更新 更多