我正在开发一个 React 应用程序,我需要根据用户当前的身份验证状态有条件地呈现“登录”或“注销”按钮。但是,我遇到了条件语句未按预期工作的问题。即使用户登录后,也只显示登录按钮,除非同时显示两个按钮,否则我无法注销,这不是所需的行为。
{ isAuthenticated ? () : () }
import React from 'react'
import { FaTruckMoving } from 'react-icons/fa';
import { AiOutlineHeart, AiOutlineUser } from 'react-icons/ai'
import { BsBagCheck } from 'react-icons/bs'
import { CiLogin, CiLogout } from 'react-icons/ci'
import './Nav.css'
import { Link } from 'react-router-dom';
import { useAuth0 } from "@auth0/auth0-react";
const Nav = () => {
const { loginWithRedirect, logout, user, isAuthenticated } = useAuth0();
let authButton;
if (isAuthenticated) {
authButton = (
);
} else {
authButton = (
);
}
return (
<>
Free Shipping for Orders upto Rs.1000
{
isAuthenticated &&
(
Hello, {user.name}
)
}
-
Home
-
Product
-
About
-
Contact
{authButton}
>
)
}
export default Nav
我尝试了上述方法,但结果仍然相同
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您没有使用
isAuthenticated的好方法,如果isAuthenticated为 True,则需要显示注销按钮,否则如果isAuthenticated为 False您需要显示登录按钮。试试这个:
{ isAuthenticated ? (<button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })}><CiLogout /></button>) : (<button onClick={() => loginWithRedirect()}><CiLogin /></button>) }