在react-router 2中禁用后退按钮

Wit*_*ult 3 javascript reactjs react-router

我正在使用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>
Run Code Online (Sandbox Code Playgroud)

一切正常,但我有问题从我的仪表板页面禁用后退按钮.

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

Oli*_*liv 14

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

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

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

回去是不可能的.


uga*_*oft 6

在您想要禁用返回的页面上(例如,在 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);
    });
}
Run Code Online (Sandbox Code Playgroud)

  • 这也适用于 useEffect 内部.. thx (2认同)

Ali*_*lia 6

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

history.replace('/Whatever_screen')
Run Code Online (Sandbox Code Playgroud)

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