使用 javascript 和 React 删除本地存储中数组中的特定元素

Delete specific element in the array in localstorage using javascript and React

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

这可能吗?我该怎么做?

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

您可以使用这 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>

在本地存储中添加一些爬虫:

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