【问题标题】:How to disable the return button without clearing the URL current address如何在不清除 URL 当前地址的情况下禁用返回按钮
【发布时间】:2021-09-26 15:18:40
【问题描述】:

我为此尝试了几种变体:
他们都不是我需要的,有些只是放手。
如何防止用户在重定向到http://localhost:3000/home 后返回,但 URL 必须保持在“/home”,并且用户不应该能够通过手动更改地址栏进行导航。
(实际上阻止了重新注册)

这些是我从其他人的问题中检查的示例。 这些都不起作用。

useEffect(() => {  //Non of these worked
 window.history.replaceState(null, null, '/');

 Or

 window.addEventListener('popstate', () => {
      history.go(1);
    });

Or

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

Or 

  window.onpopstate = function () {
    history.pushState(null, null, window.location.href);
    history.go(1);
}, []);`

在这些之后,最后一个地址可能会保持signup/mobile,然后返回会给出一个混合 - 一个缺少按钮/CSS的错误地址。

【问题讨论】:

    标签: javascript reactjs react-router browser-history


    【解决方案1】:

    你可以创建一个 react-router Guard 来阻止用户在认证后访问登录组件,这意味着认证组件需要被条件保护。

    示例:

    import React from 'react';
    import { Route, Redirect } from "react-router-dom";
    
    const GuardedRoute = ({ component: Component, auth, ...rest }) => (
        <Route {...rest} render={(props) => (
            auth === true
                ? <Redirect to='{location.pathname}' />
                : <Component {...props} />
        )} />
    )
    
    export default GuardedRoute
    

    How to create guarded routes for your React-App启发的答案

    【讨论】:

    • 嗨 Hajed,authrest 是什么?它们在哪里定义?
    • 我对@9​​87654325@感到困惑
    • Hello ExtraSun,这只是一个例子,“auth”是一个布尔对象,用于验证用户是否通过身份验证,“...rest”代表路由的额外属性(将其视为 etc aka "..." 。
    • 这个想法是将身份验证组件路由更改为受保护的路由,就像上面的示例一样,因此如果用户通过身份验证,他将无法访问回登录组件,这意味着他将留在当前路径名而且我认为如果在单击返回按钮时用户通过身份验证将其重定向到当前路由/home({location.pathname})而不清除 URL(而不是登录路由),这正是您所需要的。
    • 我试过了,没用。黑页。我的 App.js 有 SwitchRoute&lt;Route exact path='/signup'&gt; &lt;SignUp setUserNumber={setUserID} setIfSignUp={setIfSignUp} /&gt; &lt;/Route&gt; &lt;Route exact path='/home'&gt; &lt;Home userIDNumber={userID} setIfSignUp={setIfSignUp} /&gt; &lt;/Route&gt;(许多属性),我怎样才能将它们结合起来?
    猜你喜欢
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 2011-08-17
    相关资源
    最近更新 更多