[英]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.