javascript 刷新后重置本地存储值,未定义本地存储

shyt4zoc  于 2023-01-01  发布在  Java
关注(0)|答案(4)|浏览(112)

我的阵列和本地存储在每次刷新后都会重置。我看到一些答案,比如我需要解析数据,然后将其字符串化。我面临的问题是,我一直收到一条错误消息,说"未定义本地存储"和一个内部服务器错误500。
我编写了下面的代码
//对象

"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,
     }

获取对象

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

这是我的职责

//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>
mspsb9vt

mspsb9vt1#

您在错误的位置调用localStorage,即使您使用了type of window !== 'undefined',您也已经预先调用了const favs = JSON.parse(localStorage.getItem('name'))
假设这是一个React组件,您可以在useEffect调用中获取本地存储。

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是唯一的(值不重复),则将

const newFavs = [...favs, value]

改成

const newFavs = [...new Set([...favs, value])]

Reference on Set

hujrc8aj

hujrc8aj2#

您需要做的第一件事是在本地存储中设置项目:

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

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

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

应该是这样的。还要确保你在浏览器上没有处于inkognito模式,这可能会在重新加载页面时重置存储。
为了进一步说明,您的脚本将类似于以下内容:

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.

代码和框中的React示例:
Codesandbox
问候

yxyvkwin

yxyvkwin3#

这就是答案
常量favs =窗口类型!==“未定义”?JSON.parse(本地存储.getItem('name')):零||[];

gev0vcfq

gev0vcfq4#

这是我对此问题的解决方案:-

//you can use also  typeof window !== "undefined"  insted of  process.browser
const favs = process.browser ? localStorage.getItem('name') : null ; //necessary because u are using nextjs

useEffect(() => {
        if (process.browser) {
            setFavs(JSON.parse(favs || '""') || '')

 }
}, [favs])

相关问题