【问题标题】:Delete specific element in the array in localstorage using javascript and React使用 javascript 和 React 删除本地存储中数组中的特定元素
【发布时间】:2026-01-03 15:10:01
【问题描述】:

我在本地存储中有一个数组,我正在映射该数组以将其数据呈现​​到列表中。我想在列表中的每个元素旁边添加按钮,如果单击该按钮,特定元素将从本地存储中的数组中删除。

这可能吗?我该怎么做?

使用 -> Javascript 和 React 代码在这里:


//This array is in the localstorage
const reptiles = ["alligator", "snake", "lizard"];

function ReptileList() {

  return (
    <ol>
      {reptiles.map((reptile) => (
        <li>{reptile} /*THERE SHOULD BE THE DELETE BUTTON*/</li>
      ))}
    </ol>
  );
}

【问题讨论】:

  • 完全有可能,而且有很多教程教你如何在React中创建一个触发JS函数的按钮,所以从那里开始。甚至React's own tutorial 也会教你如何做到这一点,所以我强烈建议(重新)接受它。

标签: javascript arrays reactjs local-storage


【解决方案1】:

在localStorage中添加一些爬虫:

// in the Browser Console
localStorage.setItem( "reptiles", ["alligator", "snake", "lizard"] )

或添加一些其他功能以从 UI 添加爬行动物。

import "./styles.css";
import { useEffect, useState } from 'react';


export default function ReptileList() {

  const [ reptiles, setReptiles ] = useState( [] )

  function deleteReptile( name ){
    // Fin the index of the reptile
    let index = reptiles.indexOf( name )
    // if reptile is found
    if( index !== -1 ){
      // remove it from state
      reptiles.splice(index, 1 )
      // update localStorage
      localStorage.setItem( 'reptiles', reptiles )
      // update reptiles State to re-render the list
      setReptiles( [...reptiles] )
    }
  }

  function readReptiles(){
    // read from localStorage
    let reptiles = localStorage.getItem( 'reptiles' )
    
    // if no reptiles in localStorage initialize with empty
    if( reptiles === null ){
      reptiles =  []
    }
    // init reptiles State
    setReptiles( reptiles.split(',') )
  }

  useEffect(() => {
    // read reptiles from local storage after rendered
    readReptiles();
    return () => {};
  }, []);

  return (
    <div className="App">
      <h1>Reptiles</h1>
      {reptiles.map( (reptile => (
        <li key={reptile} >{reptile} - 
          <button onClick={()=>deleteReptile(reptile)}>Delete</button> 
        </li>
      )))}
    </div>
  );
}

【讨论】:

    【解决方案2】:

    您可以使用这 2 个函数从本地存储中获取和删除项目。

    const getElementsfromLocalStorage = () => {
        let elements = [];
        if (localStorage.getItem('reptiles')) {
            elements = JSON.parse(localStorage.getItem('reptiles'));
        }
        return elements;
    };
    
    const removeElementLocalStorage = (name) => {
        let elements = getElementsfromLocalStorage();
        elements = elements.filter(element => element.name !== name);
        localStorage.setItem('reptiles', JSON.stringify(elements));
    };
    

    现在,当您渲染列表时,为每个列表项渲染一个按钮,并在单击按钮时调用函数removeElementLocalStorage 并使用值。

    <li>
        <span>{reptile}</span>
        <button onClick={() =>removeElementLocalStorage(element.name)}>Remove</button>
    </li>
    

    【讨论】:

    • 非常感谢 :) 这很有帮助。我的解决方案很接近,但我在删除项目后忘记更新本地存储。