简体   繁体   English

UseEffect 在用户登录时更新导航栏?

[英]UseEffect to update navbar when user is logged in?

I'm working on a navbar that changes whenever it detects there is a user in local storage using useState and useEffect.我正在开发一个导航栏,只要它使用 useState 和 useEffect 检测到本地存储中有用户,它就会发生变化。 Here's my logic:这是我的逻辑:

const [user, setUser] = useState("")
  

  function fetchData(){
    const item = JSON.parse(localStorage.getItem('name'))
    if(item) {
      setUser(item)
    }
  }

  useEffect(() => {
      fetchData()
});

return({user? (<LoggedIn />) : (<ClientBar />)

The code essentially begins with no user, and in the fetchData() function it checks whether a user exists and sets the user as whatever it finds in local storage.代码基本上从没有用户开始,在fetchData() function 中,它检查用户是否存在并将用户设置为它在本地存储中找到的任何内容。 I can tell the logic works because when I refresh it, it changes from <ClientBar> to <LoggedIn> , but the whole reason I put it in a useEffect() was so that it would update immediately.我可以告诉逻辑是有效的,因为当我刷新它时,它从<ClientBar>变为<LoggedIn> ,但我把它放在useEffect()中的全部原因是它会立即更新。 Any advice?有什么建议吗? I know the best practice would be to put it in a global state, but I really am not sure how to set that up and I need to get this done, fast.我知道最好的做法是将它放在全局 state 中,但我真的不知道如何设置它,我需要快速完成它。 A method I've found that works is putting history.go(0) in my login function so that it refreshes on authentication, but it doesn't look too good so I'm trying to avoid it if I can.我发现一种可行的方法是将history.go(0)放入我的登录 function 以便它在身份验证时刷新,但它看起来不太好,所以我尽量避免它。 Cheers.干杯。

As Abhi Patil stated, you need to check localStorage changes.正如 Abhi Patil 所说,您需要检查 localStorage 更改。 It has nothing to do with useEffect as it is only triggered when the component is mounted.它与useEffect无关,因为它仅在安装组件时触发。

You need to wrap fetchData() inside storage event listener like so:您需要将fetchData()包装在storage事件侦听器中,如下所示:

useEffect(() => {
 window.addEventListener('storage', () => {
  const item = JSON.parse(localStorage.getItem('name'))
    if(item) {
      setUser(item)
    }
 })
})

Your useEffect should be:你的useEffect应该是:

useEffect(() => {
      fetchData()
}, [user])

So when user changes it will check each time.因此,当user更改时,它将每次检查。 Because you're fetching localstorage I'd also encourage you to add a loading component while that's being done.因为您正在获取localstorage ,所以我还鼓励您在完成时添加加载组件。

Checking localstorage Should also be using async/await:检查localstorage也应该使用 async/await:

const fetchData = async () => {
    const item = await JSON.parse(localStorage.getItem('name'))
    if(item) setUser(item)
  }

While this it's waiting for the check you should render a loading with another useState .虽然它正在等待检查,但您应该使用另一个useState渲染加载。

暂无
暂无

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

相关问题 尝试检查用户是否登录时的useEffect无限循环 - useEffect infinite loop when trying to check if user is logged in 当用户未登录时显示导航栏。希望导航栏在用户拥有令牌后呈现 - NavBar displaying when user is not logged in. Want navbar to render after user has token 为登录用户显示不同的导航栏 - Display different navbar for logged user 一旦用户使用 React 和 Firebase 登录(从“登录”到“个人资料”),我如何更新我的导航栏? - How do I update my NavBar once a user is logged-in (from 'log in' to 'profile') using React & Firebase? 如果用户登录或未登录,实现条件导航栏的策略 - Strategies to implementing a conditional Navbar if a user is logged in or not Vue.js:无论用户是否登录,导航栏上的显示/隐藏按钮均基于Vuex商店状态 - Vue.js: Show/Hide buttons on navbar based on Vuex Store state when the user is logged in or not 在多个浏览器中登录后,如何更新更改的用户数据 - How to update changed user data, when Logged In in several browsers React - 用户登录后如何在导航栏中隐藏注册/登录? - React - How to hide register/login in navbar once a user has logged in? 根据用户是否登录来显示不同导航栏的方法是什么? - What are the ways to show different navbar based on if the user logged or not? 根据用户是否登录在 React 中更改 Navbar 值的正确方法是什么? - What is the correct way to change Navbar values in React based on if user is logged in?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM