【问题标题】:How to remove item from array stored in localstorage if the item already exists and changing state of button如果项目已经存在并更改按钮状态,如何从存储在本地存储中的数组中删除项目
【发布时间】:2020-04-09 17:01:15
【问题描述】:

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

组件:

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 会重新加载一些奇怪的页面,所以它实际上只是上一个正在运行的错误或正在发生的事情..? ._.

【问题讨论】:

    标签: javascript reactjs local-storage react-tsx


    【解决方案1】:

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

    虽然,如果您有多个 AddFavorite 组件正在呈现,我修改它的方式将失败,因为当不同的组件进行更改时,收藏夹数组不会更新。

    为了让组件在其他组件进行更改时得到更新,我建议使用 redux、上下文,或者只是在父组件中维护收藏夹数组。

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

    【讨论】:

    • 非常感谢您的帮助和推荐!我最终使用了 context ,它就像魔术一样工作:)
    猜你喜欢
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 2013-09-12
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多