gpt4 book ai didi

javascript - 如果项目已存在并且更改按钮状态,如何从本地存储中存储的数组中删除项目

转载 作者:行者123 更新时间:2023-12-02 21:09:55 25 4
gpt4 key购买 nike

在天气应用程序中,我尝试创建添加到收藏夹功能。到目前为止,它可以部分工作,但有一些我似乎无法解决的错误,因为我真的不明白是什么导致了它们。

组件:

import React, { ReactNode, useState } from 'react';
interface Props {
location?: string;
}
export const AddFavorite: React.FC<Props> = ({ location }: Props) => {
let favorites: any = [];
// const [favorite, setFavorite] = useState(false);
const toggleFavoriteBtn = () => {
const storageFavorites = localStorage.getItem('favorites');
const index: number = favorites.indexOf(location);

favorites = storageFavorites ? JSON.parse(storageFavorites) : [];
if (index > -1) {
favorites.splice(index, 1);
// setFavorite(false);
} else {
favorites.push(location);
// setFavorite(true);
}
localStorage.setItem('favorites', JSON.stringify(favorites));
};
return (
<div>
<button type="button" onClick={toggleFavoriteBtn}>
{/* {favorite ? 'favorited' : 'not favorited'} */}
favorite
</button>
</div>
);
};

目前,我已经注释掉了 useState 部分,但稍后我会讨论它。

基本上,如果我运行此代码并测试按钮,我可以添加和删除位置而不会出现任何问题,除非我重新加载页面或添加另一个位置,然后返回到我之前添加的位置。然后突然间,我的数组不再理解该位置已经在数组中,并再次添加它,此后它就变得疯狂,没有任何逻辑意义。

这是代码开始设置的方式还是我错过了一些事情?

其次,我添加了 useState 部分,该部分现在已被注释掉,因为我想使用它的全部原因是能够在该位置被收藏或不收藏时更改按钮的外观。然而,它完全破坏了我的功能(尽管我不明白为什么它甚至会影响它),并且不是以正常方式删除和添加项目,而是每次点击它都会进入以下不合逻辑的循环:

  1. 添加位置
  2. 再次添加位置(所以现在是 数组中两次)
  3. 删除重复位置之一

(每一步都是一次点击)因此,下次您点击 3 次时,同一位置还剩下 2 个,下一次还有 3 个,依此类推。

这可能是因为 useState 做了一些奇怪的页面重新加载,所以它实际上只是之前正在运行的错误或正在发生的事情..? ._.

最佳答案

您遇到的最大问题是在构建组件时没有从 localStorage 加载收藏夹数组。

尽管如此,如果您要渲染多个 AddFavorite 组件,我修改此组件的方式将会失败,因为当不同组件进行更改时,收藏夹数组不会更新。

为了让组件在其他组件发生更改时更新,我建议使用 redux、context,或者仅在父组件中维护收藏夹数组。

import React, { ReactNode, useState, useEffect } from 'react';
interface Props {
location?: string;
}
export const AddFavorite: React.FC<Props> = ({ location }: Props) => {
let [favorites, setFavorites] = useState(():any[]=>JSON.parse(localStorage.getItem('favorites')||'[]'));
const favorite = favorites.includes(location);
// const [favorite, setFavorite] = useState(false);
useEffect(() => {
const funct = ()=>{
setFavorites(JSON.parse(localStorage.getItem('favorites')||'[]'));
};
window.addEventListener('storage',funct);
return () => {
window.removeEventListener('storage',funct);
}
}, [])
const toggleFavoriteBtn = () => {
const index: number = favorites.indexOf(location);
const newFavorites = favorites.slice();
if (index > -1) {
newFavorites.splice(index, 1);
// setFavorite(false);
} else {
newFavorites.push(location);
// setFavorite(true);
}
setFavorites(newFavorites);
localStorage.setItem('favorites', JSON.stringify(newFavorites));
};
return (
<div>
<button type="button" onClick={toggleFavoriteBtn}>
{favorite ? 'favorited' : 'not favorited'}
favorite
</button>
</div>
);
};

关于javascript - 如果项目已存在并且更改按钮状态,如何从本地存储中存储的数组中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61126374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com