每次刷新后,我的数组和本地存储继续重置。我看到了一些答案,比如我需要解析数据,然后将其串成字符串。我面临的问题是,我一直收到一条错误消息,上面写着“没有定义本地存储”和一个内部服务器错误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>发布于 2022-02-06 19:28:40
您在错误的位置调用localStorage,即使您使用了type of window !== 'undefined',您已经提前调用了const favs = JSON.parse(localStorage.getItem('name'))。
假设这是一个反应组件。您可以在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])]发布于 2022-02-06 13:35:32
首先,需要做的是在本地存储中设置项:
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.在代码框中作出反应:
问候
发布于 2022-02-07 17:33:08
这就是答案
==“未定义”?JSON.parse(localStorage.getItem('name')):null _
https://stackoverflow.com/questions/71007637
复制相似问题