簡體   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