繁体   English   中英

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

[英]How to remove item from array stored in localstorage if the item already exists and changing state of button

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

零件:

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 部分,但我稍后会谈到。

几乎,如果我运行此代码并测试按钮,我可以毫无问题地添加和删除一个位置,除非我重新加载页面或例如添加另一个位置,然后 go 回到我之前添加的位置。 然后突然间,我的数组不再理解该位置已经在数组中,并再次添加它,然后它就变成了香蕉,没有任何逻辑意义。

是代码设置的方式开始还是我错过了什么?

其次,我添加了现在被注释掉的 useState 部分,因为我想要使用它的全部原因是能够在该位置是否被收藏时更改按钮的外观。 然而,它完全破坏了我的 function (我不明白为什么它甚至会影响它),而不是在正常情况下删除和添加一个项目,每次点击它只是进入这个不合逻辑的循环:

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

(每一步都是一次点击)所以下一次点击3次,同一位置剩下2个,下一次有3个,以此类推..

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

您遇到的最大问题是在构建组件时没有从 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>
  );
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM