[英]What are the ways to show different navbar based on if the user logged or not?
[英]Display different navbar for logged user
我已经在我的应用程序中创建了登录/注册,现在我想根据用户登录显示不同的导航栏。 我不为这个项目使用 redux。
在全局的 App 组件中,我创建了 state 我想传递给孩子,然后基于它,显示不同的数据,所以我创建了这样的东西:
function App() {
const [loginStatus, setLoginStatus] = useState();
useEffect(() => {
if(!loginStatus) {
axios.get("http://localhost:5000/api/users/isUserAuth", {
headers: {
"x-access-token": localStorage.getItem("token")
}
}).then((response) => {
console.log(response);
setLoginStatus(true);
})
}}, [])
然后在我的导航栏中我创建了这样的东西:
<NavItem style={{display: loginStatus ? "block" : "none"}}>
这有效,但它会导致 loginStatus 每次页面刷新,每条路由都被加载,所以当我 go 在用户登录时转到不同的页面时,它会在 NavItem 出现之前导致 0.5 秒的延迟,因为它会在每次刷新时向后端发出请求。
我如何存储用户登录的信息,这样就不必在每个页面上进行 API 调用?
我认为您可以使用localStorage
来存储用户登录信息。
您需要使用本地存储令牌初始化 state 并检查该 state
const [loginStatus, setLoginStatus] = useState(token)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.