首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >未定义刷新后重置的本地存储值,也未定义区域存储。

未定义刷新后重置的本地存储值,也未定义区域存储。
EN

Stack Overflow用户
提问于 2022-02-06 13:26:49
回答 3查看 5.4K关注 0票数 2

每次刷新后,我的数组和本地存储继续重置。我看到了一些答案,比如我需要解析数据,然后将其串成字符串。我面临的问题是,我一直收到一条错误消息,上面写着“没有定义本地存储”和一个内部服务器错误500。

我已经写了下面的代码

//对象

代码语言:javascript
复制
"items": [
    {
      "id": 119603782,
      "node_id": "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
      "name": "react-contextual",
      "full_name": "drcmda/react-contextual",
      "private": false,
     },
{
      "id": 119603782,
      "node_id": "MDEwOlJlcG9zaXRvcnkxMTk2MDM3ODI=",
      "name": "react-contextual",
      "full_name": "drcmda/react-contextual",
      "private": false,
     }

获取对象

代码语言:javascript
复制
export async function getServerSideProps() {
  const res = await fetch(
    "https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc"
  );
  const data = await res.json();

  return {
    props: {
      data,
    },
  };
}

这是我的职责

代码语言:javascript
复制
//trying to keep the values after a page refresh
const favs = JSON.parse(localStorage.getItem('name')) || [];


//localstorage is not defined 
//define it here 
const storage = typeof window !== 'undefined'? localStorage.getItem('name') : null


 

//check for value then store it in array and to local storage
function checkId (e) {
 if(e.target.value !==  ""){
   favs.push(e.target.value)
 //check if it exists  
localStorage.getItem('name') === null
 //if exists store it  
localStorage.setItem('name', JSON.stringify(favs))
   console.log(favs);
   

 } 
}




    <div className="grid grid-cols-3 rows-2 text-lg font-bold">
         {storage}
    
    </div>

<div className="grid grid-cols-3 grid-rows-2 gap-2 bg-black text-white border-white">
        {data.items
          .sort(function (a, b) {
            return  new Date (b.created_at) - new Date(a.created_at) || a.stargazers_count - b.stargazers_count  
          })
          .map((d) => (
            

    <button id="btn" onClick={checkId} value={d.name}>Favorite me </button>
EN

回答 3

Stack Overflow用户

发布于 2022-02-06 19:28:40

您在错误的位置调用localStorage,即使您使用了type of window !== 'undefined',您已经提前调用了const favs = JSON.parse(localStorage.getItem('name'))

假设这是一个反应组件。您可以在useEffect调用中获取本地存储。

代码语言:javascript
复制
const Component = () => {
     const [ fav,setFavs ] = useState([]);
     
     useEffect(() => {
           if (typeof window !== 'undefined') { //necessary because u are using nextjs
                const storage = localStorage.getItem('name');
                if (storage) {
                     setFavs(JSON.parse(storage));
                     //favs will be populated with your localStorage once, on component mount.
                }
           }
     },[])

     const checkId = (e.target.value) => {
          const value = e.target.value;
          if (!value) return;

          const newFavs = [...favs, value]
          localStorage.setItem('name', JSON.stringify(newFavs));
          setFavs(newFavs);
     }
   

     .....

     return (<pre>{ JSON.stringify(favs, null, 4)}</pre>)
}

奖金

如果您希望您的favs是唯一的(值不重复),那么

代码语言:javascript
复制
const newFavs = [...favs, value]

把它改成

代码语言:javascript
复制
const newFavs = [...new Set([...favs, value])]

集上参考

票数 1
EN

Stack Overflow用户

发布于 2022-02-06 13:35:32

首先,需要做的是在本地存储中设置项:

代码语言:javascript
复制
function setItem(key, item) {
    localStorage.setItem(key, JSON.stringify(item));
}

现在,在刷新页面之后,您可以从本地存储中检索它:

代码语言:javascript
复制
function getItem(key) {
    const item = localStorage.getItem(key);
    return JSON.parse(item);
}

应该是这样的。还要确保浏览器上没有处于inkognito模式,这可能会在重新加载页面时重置存储空间。

为了进一步澄清,您的脚本应该如下所示:

代码语言:javascript
复制
const myTestItem = 'test item';

function setItem(key, item) {
    localStorage.setItem(key, JSON.stringify(item));
}

function getItem(key) {
    const item = localStorage.getItem(key);
    return JSON.parse(item);
}

setItem('test', myTestItem);

// after reload you can check wether it's there.
console.log(getItem('test')); // <-- just to log it to console, also u could check the application tab in chrome console and check the localstorage.

在代码框中作出反应:

码箱

问候

票数 0
EN

Stack Overflow用户

发布于 2022-02-07 17:33:08

这就是答案

==“未定义”?JSON.parse(localStorage.getItem('name')):null _

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71007637

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档