繁体   English   中英

禁用反应路由器 2 中的后退按钮

[英]disable back button in react-router 2

我正在使用 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后退按钮。

最好的办法是,当用户登录时,他/她会被重定向到 dashbaord。 如果由于某种原因用户单击后退按钮,您应该:

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

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

再也回不去了。

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

history.replace('/Whatever_screen')

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

在您要禁用的页面上(例如,在 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);
    });
}

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

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

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

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

在您的登录屏幕中将替换添加到 /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。 在添加之前,请确保您正确设置了身份验证。

为了提高代码的可重用性,我们可以在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"));
}

无法禁用浏览器按钮。 但是我们可以使用诸如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);

更多信息:禁用反应返回按钮

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM