使用LocalStorage显示或隐藏元素



我正在尝试创建一个具有多种用户类型的网络应用程序,这些用户类型因当前登录的用户而异。我遇到的问题如下:

当用户单击一张卡时,会显示一个包含该卡更多详细信息的对话框。在这个对话框中,我想有一个只呈现给特定用户的部分,在这种情况下,该用户是管理员。我该怎么做?

我当前的代码包含以下内容:

// Gets the item from the storage correctly
if(localStorage.getItem("role") == "Administrator"){
alert('This currenly works');
//Show table that is not shown to other types of user, the getItem must result in Administrator in order to show the part of the component
}
//Shown to all users of the webapp
<div className="w-[70vw] max-w-[800px] relative">
<a
className="absolute -right-4 -top-4 rounded-full bg-white shadow-lg w-10 h-10 hover:bg-gray-200 hover:cursor-pointer transition flex justify-center items-center z-99"
onClick={resetDialog}
>
X
</a>
<h1 className="font-bold text-2xl border-b p-4">
{item_name}
</h1>
<div className="grid grid-cols-2 h-[240px] w-full relative">
<div className="h-[240px] p-4">
<div className="h-full w-full relative">
<img
src={image}
className="rounded-lg max-w-full max-h-full m-auto absolute top-0 left-0 right-0 bottom-0 shadow-lg"
/>
</div>
</div>
<div className="h-[240px] flex flex-col relative">
<div className="max-h-full overflow-auto p-4">
{item_description}
</div>
</div>
<div className="absolute bottom-[-16px] right-4 z-20">
<LoadingButton
onClick={onAddToCart}
isLoading={loadingAddToCart}
text="Add to cart"
className="w-48"
/>
</div>
</div>
//Should only be shown if the user is an Administrator
{/* <div>
<div
className={`${style.customTableRow} ${style.header} pr-4`}
>
<span>Name</span>
<span>Location</span>
<span>Availability</span>
</div>
<div className="max-h-[170px] overflow-auto">
{models.map((model) => (
<div
className={`${style.customTableRow} border-t`}
>
<span>{model.model}</span>
<span>{model.location_name}</span>
<span>
{getAvailabilityPill(model.availability)}
</span>
<div className="flex justify-center">
<button
className="flex bg-green-500 rounded-full hover:bg-green-300 transition text-white p-1"
onClick={() => addRequest(model.id)}
>
<i className="fa-solid fa-plus"></i>
</button>
</div>
</div>
))}
</div>
</div> */} //End of content for Administrator
</div>

欢迎提出任何建议。

您可以通过制作一个简单的标志来实现这一点,该标志表示用户是否是管理员。如果用户是管理员,它将呈现管理员特定的内容,否则它将呈现网站上的正常内容。看看这个代码

const [ isAdmin , SetIsAdmin ] = useState(false)
useEffect ( ()=> { SetIsAdmin(localStorage.getItem("role") == "Administrator") } , [])
return (
{isAdmin ? <> Admin </> : <> User </>}
)
// ! don't forget to import hooks

您可以有条件地呈现内容,

{isUserAdmin && <SpecialAdminContent />}

将仅为管理员用户显示内容。

最新更新