[英]Delete specific element in the array in localstorage using javascript and React
我在 localstorage 中有一個數組,我正在映射數組以將其數據呈現到列表中。 我想在列表中的每個元素旁邊添加按鈕,如果單擊該按鈕,則特定元素將從本地存儲中的數組中刪除。
這可能嗎?我該怎么做?
在此處使用 -> 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));
};
現在,當您渲染列表時,使用每個列表項渲染一個按鈕,並在單擊該按鈕時調用 function removeElementLocalStorage
值。
<li>
<span>{reptile}</span>
<button onClick={() =>removeElementLocalStorage(element.name)}>Remove</button>
</li>
在 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>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.