简体   繁体   English

为登录用户显示不同的导航栏

[英]Display different navbar for logged user

I've created login/register in my app, and now i want to display different navbar based if user is logged.我已经在我的应用程序中创建了登录/注册,现在我想根据用户登录显示不同的导航栏。 I don't use redux for this project.我不为这个项目使用 redux。

In App component, globally, i created state that i wanted to pass to childs, and then base on it, display different data, so i created something like this:在全局的 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);
      })
    }}, [])

and then in my Navbar i created something like this:然后在我的导航栏中我创建了这样的东西:

      <NavItem style={{display: loginStatus ? "block" : "none"}}>

This works, but it causes loginStatus to be loaded every page refresh, every route made, so when i go to different page when user is logged, it causes 0.5s delay before NavItem will appear, because it makes request to backend on every refresh.这有效,但它会导致 loginStatus 每次页面刷新,每条路由都被加载,所以当我 go 在用户登录时转到不同的页面时,它会在 NavItem 出现之前导致 0.5 秒的延迟,因为它会在每次刷新时向后端发出请求。

How can i store information that user is logged in so it wouldn't have to make API calls on every page?我如何存储用户登录的信息,这样就不必在每个页面上进行 API 调用?

I think you can use localStorage to store user logged-in information.我认为您可以使用localStorage来存储用户登录信息。

You need to initialize state with the local storage token and check with that state您需要使用本地存储令牌初始化 state 并检查该 state

const [loginStatus, setLoginStatus] = useState(token)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM