【问题标题】:How to make a localStorage not reset when the app renders?如何在应用程序呈现时使 localStorage 不重置?
【发布时间】:2020-04-05 07:55:33
【问题描述】:

我创建了一个 localStorage,每次用户访问我的应用时都会添加 +1。问题是每次我刷新页面,值都会回到0。

这是我的代码:

  localStorage.setItem('timesVisited', 0);

  useEffect(() => {
      if (localStorage.getItem('timesVisited') < 5) {
      let timesVisited = parseInt(localStorage.getItem('timesVisited'));
      localStorage.setItem('timesVisited', ++timesVisited);
    }
},[])

这个想法是让 localStorage 总和 +1 直到它达到 5 但它保持为 0。我做错了什么?

【问题讨论】:

  • 那是因为它与您的浏览器有关,而不是您的代码。
  • @ZombieChowder 有什么解决方法吗?

标签: javascript reactjs local-storage


【解决方案1】:

此行将始终运行并重置任何先前的值

localStorage.setItem('timesVisited', 0);

把它变成

if(!localStorage.getItem('timesVisited')){
  localStorage.setItem('timesVisited', 0)
}

【讨论】:

  • 我知道这是问题所在。我应该采用什么解决方案来解决这个问题?
  • @ncesar 通过在其顶部添加一个 if 块
【解决方案2】:

尝试这样的事情,如果没有设置localstorage,则设置为0,否则递增

 useEffect(() => {
   if (!localStorage.getItem('timesVisited')) {
     localStorage.setItem('timesVisited', 0);
   } else if (localStorage.getItem('timesVisited') < 5) {
     let timesVisited = parseInt(localStorage.getItem('timesVisited'));
     localStorage.setItem('timesVisited', ++timesVisited);
   }
 }, [])

【讨论】:

    【解决方案3】:

    如果您在组件主体中提供的行,那么不仅每次用户访问您的应用时都会调用它,而且每次组件呈现时都会调用它。

    对于您要查找的行为,您应该加载该值,如果不存在则将其设置为 0。您也应该在组件之外执行此操作。

    另外,请注意 localStorage 仅存储字符串,因此您需要解析从中获取的内容。

        const storedValue = localStorage.getItem('timesVisited')
        // localStorage only stores string
        const visitsCount = storedValue ? parseInt(storedValue) : 0
    
        function myComponent = () => {
            useEffect(() => {
                if(visitsCount >= 5){ 
                    return
                }
                localStorage.setItem('timesVisited', ++visitsCount);
            }, [])
        } 
    
    

    【讨论】:

      猜你喜欢
      • 2016-07-26
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 2019-03-13
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多