【问题标题】:Weird behaviour of React component that writes to cookies写入 cookie 的 React 组件的奇怪行为
【发布时间】:2021-08-12 22:58:05
【问题描述】:

我有一个简单的组件,它写入 cookie。最小的工作示例:

function App() {

  // stores cookie
  function setCookie(name: string, value: string, days: number) {
     ...
  }
  // reads cookie
  function getCookie(name: string) {
    ...
  }

  const cookieName = 'testCookie';

  const cookieValue = getCookie(cookieName);
  console.log('cookie value ', cookieValue);

  if (!cookieValue) {
    console.log('going to set cookie');
    setCookie(cookieName, 'test', 1);
    return <h2>Cookie was stored</h2>;
  }

  return <h2>Cookie already exists</h2>
}

export default App;

所以我想在第一次运行时设置 cookie 并让用户知道它与Cookie was stored 输出一起存储。在第二次运行时,将显示Cookie already exists

但是,即使代码执行并记录going to set cookie,我也会立即看到Cookie already existsCookie was stored 永远不会显示。

我认为发生了重新渲染,但由于 cookie value 仅记录一次,因此不一定是完全重新渲染。

如果您知道为什么会出现这种情况,请告诉我。 非常感谢!

【问题讨论】:

    标签: javascript reactjs cookies


    【解决方案1】:

    您可以通过将其存储在状态变量中来解决此问题:

    import {useState, useEffect} from 'react'
    function App() {
    
        // stores cookie
      function setCookie(name: string, value: string, days: number) {
         ...
      }
      // reads cookie
      function getCookie(name: string) {
        ...
      }
    
      const [cookieState, setCookieState] = useState(null)
    
      useEffect(() => {
        const cookieName = 'testCookie';
    
        const cookieValue = getCookie(cookieName);
        console.log('cookie value ', cookieValue);
    
        if (!cookieValue) {
          console.log('going to set cookie');
          setCookieState(cookieName, 'test', 1);
        }
       }, [])
    
      return cookie ? <h2>Cookie already exists</h2> : <h2> Cookie doesn't exist </h2>
    }
    
    export default App;
    

    【讨论】:

    • 感谢您抽出时间帮助我。您的解决方案有一个小缺点 - 一旦存储了 cookie,它就会重新呈现组件。这不是我想要得到的用例。我的用例如下: 1. 用户看到Cookie was stored 屏幕(并存储了 cookie) 2. 刷新页面后,我读取了 cookie,然后显示另一条消息 基本上我需要保持状态直到页面重新加载。
    • setCookie 状态设置器和setCookie 自定义函数具有相同的标识符,因此在此示例中使用它是不明确的,尽管它看起来像基于参数数量的自定义函数。
    • 我已经通过引入useStateuseEffect解决了这个问题。没有这些,重新渲染就会发生,但是以一种非常不可预测的方式。
    猜你喜欢
    • 2013-11-27
    • 2016-12-15
    • 2020-11-04
    • 2020-03-26
    • 2014-03-03
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多