Nextjs:移除 cookie 时组件不会更新 DOM,而是在添加 cookie 时更新

问题描述

我在 <Navbar /> 中的 <Component {...pageProps} /> 之上添加一个 _app.js 组件。登录成功后,我添加一个 cookie Cookies.set('isLoggedIn',true,..),它将 DOM 从显示 LoginSignup 更新为在导航栏上显示 logout 按钮。但是当我点击 logout 时,这个 isLoggedin cookie 被删除,因此,DOM 现在应该在导航栏上再次显示 LoginSignup。相反,它一直显示 logout

那么,如何刷新 DOM 以便在删除 cookie 时显示 LoginSignup

登录代码,设置cookie成功:

axios
  .post(url,data,{ withCredentials: true },(Headers = config))
  .then(Cookies.set('isLoggedIn',{ 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>
  );
});

这很可能是一个水化问题,因为更改的状态是通过 console.log() 输出来的,但它并没有改变 DOM。

解决方法

如果 props / state 没有变化,React 组件无法重新渲染。

因此,您的 isLoggedIn 变量必须是该组件状态的一部分。

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>
  );
});