【发布时间】:2022-02-08 01:33:08
【问题描述】:
我的阵列和本地存储在每次刷新后都会不断重置。我已经看到了一些答案,例如我需要解析数据然后对其进行字符串化。我面临的问题是我不断收到一条错误消息,提示“未定义本地存储”和内部服务器错误 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>
【问题讨论】:
-
你评论了
setItem(key, value)函数? -
不,只是在stackoverflow上增加了vscode的清晰度,它不存在。
-
我现在已经添加了对象和调用函数的元素。
标签: javascript arrays reactjs next.js local-storage