Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果项已经存在并正在更改按钮的状态,如何从存储在localstorage中的数组中删除该项_Javascript_Reactjs_Local Storage_React Tsx - Fatal编程技术网

Javascript 如果项已经存在并正在更改按钮的状态,如何从存储在localstorage中的数组中删除该项

Javascript 如果项已经存在并正在更改按钮的状态,如何从存储在localstorage中的数组中删除该项,javascript,reactjs,local-storage,react-tsx,Javascript,Reactjs,Local Storage,React Tsx,在一个天气应用程序中,我尝试创建一个“添加到收藏夹”功能。到目前为止,它部分工作,但与一些错误,我似乎无法解决,因为我真的不知道是什么,甚至导致他们 组成部分: import React, { ReactNode, useState } from 'react'; interface Props { location?: string; } export const AddFavorite: React.FC<Props> = ({ location }: Props) =>

在一个天气应用程序中,我尝试创建一个“添加到收藏夹”功能。到目前为止,它部分工作,但与一些错误,我似乎无法解决,因为我真的不知道是什么,甚至导致他们

组成部分:

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>
  );
};
import React,{ReactNode,useState}来自“React”;
界面道具{
位置?:字符串;
}
export const AddFavorite:React.FC=({location}:Props)=>{
让收藏夹:any=[];
//const[favorite,setFavorite]=useState(false);
常量toggleFavoriteBtn=()=>{
const-storageFavorites=localStorage.getItem('favorites');
常量索引:number=favorites.indexOf(位置);
收藏夹=storageFavorites?JSON.parse(storageFavorites):[];
如果(索引>-1){
收藏夹.拼接(索引,1);
//setFavorite(false);
}否则{
收藏夹。推送(位置);
//setFavorite(真);
}
setItem('favorites',JSON.stringify(favorites));
};
返回(
{/*{favorite?'favorited':'not favorited'}*/}
最喜欢的
);
};
现在,我已经注释掉了useState部分,但我将在稍后讨论

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

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

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

  • 添加位置
  • 再次添加位置(因此现在 (阵列中有两次)
  • 删除重复位置之一
  • (每一步都是一次点击) 因此,下次单击3次时,仍有2个位置相同,下次单击3次,依此类推


    这可能是因为useState进行了一些奇怪的页面重新加载,所以实际上只是上一个正在运行的bug或正在发生的事情

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

    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>
      );
    };
    
    尽管如此,如果渲染了多个AddFavorite组件,我修改该组件的方式将失败,因为当其他组件进行更改时,favorites数组将不会更新

    为了让组件在进行更改的其他组件上更新,我建议使用redux、context,或者只是在父组件中维护favorites数组

    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>
      );
    };
    
    import React,{ReactNode,useState,useffect}来自'React';
    界面道具{
    位置?:字符串;
    }
    export const AddFavorite:React.FC=({location}:Props)=>{
    让[favorites,setFavorites]=useState(():any[]=>JSON.parse(localStorage.getItem('favorites')| |'[]);
    const favorite=收藏夹。包括(位置);
    //const[favorite,setFavorite]=useState(false);
    useffect(()=>{
    常量函数=()=>{
    setFavorites(JSON.parse(localStorage.getItem('favorites')| |'[]);
    };
    window.addEventListener('storage',funct);
    return()=>{
    window.removeEventListener('storage',funct);
    }
    }, [])
    常量toggleFavoriteBtn=()=>{
    常量索引:number=favorites.indexOf(位置);
    const newFavorites=favorites.slice();
    如果(索引>-1){
    新收藏夹。拼接(索引,1);
    //setFavorite(false);
    }否则{
    newFavorites.push(位置);
    //setFavorite(真);
    }
    设置收藏夹(新收藏夹);
    setItem('favorites',JSON.stringify(newFavorites));
    };
    返回(
    {最喜欢的?'favorited':'not favorited'}
    最喜欢的
    );
    };
    
    非常感谢您的帮助和推荐!我最终使用了上下文,它就像魔术一样工作:)