![](/img/trans.png)
[英]How can I conditionally render this component based on whether or not there is data in 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.