【问题标题】:How to redirect to home page after logout in React在 React 中注销后如何重定向到主页
【发布时间】:2021-10-18 08:35:06
【问题描述】:

我有一个简单的 react 应用程序,之后我尝试注销并重定向到主页,所以我不知道为什么它不能按预期工作,请有人帮助我。

这是我的代码:

PrivateRoute.jsx

const PrivateRoute = ({ component: RouteComponent, ...rest }) => {
    const { currentUser } = useContext(AuthContext);
    return (
        <Route
        {...rest}
        render={
            routeProps =>
            !!currentUser ? (
                <RouteComponent {...routeProps} />
            ) :(
                <Redirect to={"/"} />
            )
        }
        />
    );
};

Navbar.jsx

  const handleLogOut = () => { 
          
        fire
            .auth()
            .signOut();
        localStorage.clear();
        console.log("Logout successful");

        }

【问题讨论】:

    标签: reactjs react-router react-hooks react-router-dom


    【解决方案1】:

    您必须使用 useState() 钩子将身份验证的布尔值保持在状态,然后使用 !isAuth &amp;&amp; &lt;Redirect to="/"/&gt; 重定向 来自 react-router 库

    【讨论】:

    • 我添加了 const [isAuth, setAuth] = useState(true);在导航上我添加了 !isAuth && 但仍然不起作用
    • 现在您将其设置为 true,并且您想检查它是否为 false(用户已注销)。我只是给了你一个例子,继续玩吧
    • 在handlelogout中我设置为false,好的,谢谢
    【解决方案2】:
        const {currentUser} = useContext(AuthContext)
    
    return (
     <div>
             {currentUser ? (
      <li ><NavLink to={"/"}  exact className="Nav_link" activeStyle={{ color: 'white'}} onClick={handleLogOut}>Logout </NavLink> </li>
                                  ) : (
      <li ><NavLink to={"/login"} className="Nav_link" activeStyle={{ color: 'white'}}>Login </NavLink> </li>
             )}
    </div>)
    

    【讨论】:

      猜你喜欢
      • 2015-08-09
      • 2017-08-22
      • 2019-07-02
      • 2014-02-10
      • 2020-04-16
      • 1970-01-01
      • 2021-11-26
      • 2011-07-08
      • 2014-08-16
      相关资源
      最近更新 更多