[英]Delete specific element in the array in localstorage using javascript and React
I have an array in localstorage and I am maping the array to render it's data into list.我在 localstorage 中有一个数组,我正在映射数组以将其数据呈现到列表中。 I want to add button next to every element in the list and if I click the button the specific element gets deleted from the array in the localstorage.我想在列表中的每个元素旁边添加按钮,如果单击该按钮,则特定元素将从本地存储中的数组中删除。
Is this possible and how can I do it?这可能吗?我该怎么做?
Using -> Javascript and React code here:在此处使用 -> 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>
);
}
You can use these 2 functions to Get and Remove Items from Local Storage.您可以使用这 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));
};
Now, when you are rendering the list, render a button with every list item and call the function removeElementLocalStorage
when the button is clicked with the value.现在,当您渲染列表时,使用每个列表项渲染一个按钮,并在单击该按钮时调用 function removeElementLocalStorage
值。
<li>
<span>{reptile}</span>
<button onClick={() =>removeElementLocalStorage(element.name)}>Remove</button>
</li>
Add some reptiles in the localStorage:在 localStorage 中添加一些爬虫:
// in the Browser Console
localStorage.setItem( "reptiles", ["alligator", "snake", "lizard"] )
Or add some other functionalities to Add reptiles from the UI.或者添加一些其他功能以从 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>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.