I'm trying to rerender component when localStorage changes by changing state. The problem is if I set state inside useEffect
hook page doesn't rerender. If I put it outside useEffect
I get infinite loop. I'm sure localStorage changes because I'm getting wanted results when refreshing page. Here is my code snippet:
function Header(props) {
const [auth, setAuth] = useState({loggedIn : false})
useEffect(() => {
if (localStorage.getItem('auth')) {
setAuth(JSON.parse(localStorage.getItem('auth')))
}
},[])
const logOut = () => {
localStorage.removeItem('auth');
setAuth({loggedIn : false});
}
let listContainer = (
<div className={styles.LinkContainer}>
<div className={styles.NavigationLink} onClick={props.openLoginModal}>Login</div>
<div className={styles.NavigationLink} onClick={props.openRegistrationModal}>Register</div>
</div>
)
if (auth.loggedIn) {
listContainer = (
<div className={styles.LinkContainer}>
<div className={styles.NavigationLink}>Weekly plan</div>
<div className={styles.NavigationLink}>Shopping list</div>
<div className={styles.NavigationLink}>Options</div>
<div className={styles.NavigationLink} onClick={logOut}>Logout</div>
</div>
)
}
return (
<div className={styles.Container}>
<img src="/logo.png"
alt="HiFoodelity logo"
className={styles.LogoImage} />
{listContainer}
</div>
)
}
你想要做什么,因为每次组件渲染时都会调用 useEffect() ,并且你改变状态会导致组件重新渲染,这样你的组件就会处于无限渲染状态。
I solved it by removing [] from useEffect hook which executes only on page load, so instead of this:
useEffect(() => {
if (localStorage.getItem('auth')) {
setAuth(JSON.parse(localStorage.getItem('auth')))
}
},[])
I wrote it like this:
useEffect(() => {
if (localStorage.getItem('auth') && auth.loggedIn === false) {
setAuth(JSON.parse(localStorage.getItem('auth')))
}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.