我的阵列和本地存储在每次刷新后都会重置。我看到一些答案,比如我需要解析数据,然后将其字符串化。我面临的问题是,我一直收到一条错误消息,说"未定义本地存储"和一个内部服务器错误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>
4条答案
按热度按时间mspsb9vt1#
您在错误的位置调用localStorage,即使您使用了
type of window !== 'undefined'
,您也已经预先调用了const favs = JSON.parse(localStorage.getItem('name'))
。假设这是一个React组件,您可以在useEffect调用中获取本地存储。
奖金
如果希望
favs
是唯一的(值不重复),则将改成
Reference on Set
hujrc8aj2#
您需要做的第一件事是在本地存储中设置项目:
现在刷新页面后,您可以从本地存储中检索它:
应该是这样的。还要确保你在浏览器上没有处于inkognito模式,这可能会在重新加载页面时重置存储。
为了进一步说明,您的脚本将类似于以下内容:
代码和框中的React示例:
Codesandbox
问候
yxyvkwin3#
这就是答案
常量favs =窗口类型!==“未定义”?JSON.parse(本地存储.getItem('name')):零||[];
gev0vcfq4#
这是我对此问题的解决方案:-