[英]Functional component not updating DOM when updating state with useState
[英]Nextjs: Component is not updating the DOM when cookie is removed but updating when cookie is added
我在_app.js
的<Component {...pageProps} />
上添加了一個<Navbar />
組件。 登錄成功后,我添加了一個 cookie Cookies.set('isLoggedIn', true,..)
並將 DOM 從顯示Login
和Signup
更新為在導航欄上顯示Logout
按鈕。 但是當我單擊Logout
時,這個isLoggedin
cookie 被刪除,因此,DOM 現在應該在導航欄上再次顯示Login
和Signup
。 相反,它一直顯示Logout
。
那么,如何刷新 DOM 以便在刪除 cookie 時顯示Login
和Signup
?
登錄代碼,它成功設置了cookie:
axios
.post(url, data, { withCredentials: true }, (Headers = config))
.then(Cookies.set('isLoggedIn', true, { secure: true }, { sameSite: 'lax' }));
注銷代碼和 DOM 更改代碼:
const isLoggedIn = Cookies.get('isLoggedIn') ? true : false;
const handleLogout = () => {
axios
.post(devURL, (Headers = config), { withCredentials: true })
.then(Cookies.remove('isLoggedIn'));
...
};
return ({
isLoggedIn === false ? (
<div className={styles.authOpt}>
<Link href="/login">
<button className={styles.authButton}>Login</button>
</Link>
<Link href="/signup">
<button className={styles.authButton}>SignUp</button>
</Link>
</div>
) : (
<div className={styles.authOpt}>
<button className={styles.authButton} onClick={handleLogout}>
Log out
</button>
</div>
);
});
這很可能是水合問題,因為更改后的 state 是通過 console.log() output 來的,但它並沒有改變 DOM。
如果不更改props
/ state
,則無法重新渲染 React 組件。
因此,您的isLoggedIn
變量必須是該組件的 state 的一部分。
const [isLoggedIn, setIsLoggedIn] = useState(Cookies.get('isLoggedIn') ? true : false);
// --------------------------------------------^ initial value of the state retrieved from the cookies
const handleLogout = () => {
axios.post(devURL, (Headers = config), { withCredentials: true }).then(() => {
Cookies.remove('isLoggedIn');
setIsLoggedIn(false);
// -----^
});
...
};
return ({
isLoggedIn === false ? (
<div className={styles.authOpt}>
<Link href="/login">
<button className={styles.authButton}>Login</button>
</Link>
<Link href="/signup">
<button className={styles.authButton}>SignUp</button>
</Link>
</div>
) : (
<div className={styles.authOpt}>
<button className={styles.authButton} onClick={handleLogout}>
Log out
</button>
</div>
);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.