繁体   English   中英

根据 localStorage 有条件地渲染组件

[英]Conditionally render component depending on localStorage

当 localStorage 通过更改状态更改时,我正在尝试重新渲染组件。 问题是如果我在useEffect钩子页面中设置状态不会重新渲染。 如果我把它放在useEffect之外,我会得到无限循环。 我确定 localStorage 会发生变化,因为刷新页面时我得到了想要的结果。 这是我的代码片段:

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() ,并且你改变状态会导致组件重新渲染,这样你的组件就会处于无限渲染状态。

我通过从仅在页面加载时执行的 useEffect 钩子中删除 [] 来解决它,而不是这样:

useEffect(() => {
    if (localStorage.getItem('auth')) {
        setAuth(JSON.parse(localStorage.getItem('auth')))
    }
},[])

我是这样写的:

useEffect(() => {
    if (localStorage.getItem('auth') && auth.loggedIn === false) {
        setAuth(JSON.parse(localStorage.getItem('auth')))
    }
})

暂无
暂无

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

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