我希望過濾一個陣列并回傳除被點擊的元素之外的陣列的所有元素,所以我有一個串列元素的地圖,每個元素都有一個key={index}他們的地圖,onClick它應該呼叫我的洗掉函式,并傳入要洗掉的元素的索引,然后我需要過濾該陣列,洗掉元素,更新狀態,并將此資訊發送到我的后端。
這是洗掉功能
const deleteItem = (id) => {
// use filter, to loop through all pieces of index
const element = list.todoItems.indexOf(id - 1);
setList({ todoItems: list.todoItems.filter(element !== id) });
console.log(list.todoItems);
dispatch(updateTodo(list));
};
這是映射的陣列
{list.todoItems.map((Item, index) => (
<div
// setup anonymous function, that will call
// ONLY when the div
// is clicked on.
key={index}
onClick={() => deleteItem(index)}
>
{/* list item, gets text from props */}
<li>{Item}</li>
</div>
))}
我一定遺漏了一些東西,因為這應該可行,雖然我可能需要換檔并將每個專案作為我資料庫中的實際物件,但我不想這樣做,因為我覺得字串陣列更適合這個應用程式.
uj5u.com熱心網友回復:
洗掉您的 indexOf 邏輯,這將起作用。
您不必查找陣列的索引,因為您已經將它作為引數接收了。
const deleteItem = (id) => {
setList({ todoItems: list.todoItems.filter((_, id) => element !== id) });
console.log(list.todoItems);
dispatch(updateTodo(list));
};
uj5u.com熱心網友回復:
您不需要從 indexOf 函式的索引中減去一個
在這種情況下,拼接比過濾效果更好
const deleteItem = (id) => {
const element = list.todoItems.indexOf(id);
setList({ todoItems: {...list}.todoItems.splice(element, 1)});
dispatch(updateTodo(list));
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390690.html
標籤:javascript 数组
