使用钩子从数组中移除对象(useState)

我有一个对象数组。我需要添加一个函数来从数组中删除一个对象,而不使用“ this”关键字。

我试过使用 updateList(list.slice(list.indexOf(e.target.name, 1)))。它删除了数组中除了最后一项之外的所有内容,我不知道为什么。

const defaultList = [
{ name: "ItemOne" },
{ name: "ItemTwo" },
{ name: "ItemThree" }]


const [list, updateList] = useState(defaultList);


const handleRemoveItem = e => {
updateList(list.slice(list.indexOf(e.target.name, 1)))
}


return (
{list.map(item => {
return (
<>
<span onClick={handleRemoveItem}>x </span>
<span>{item.name}</span>
</>
)}
}


)


预期: 单击的项目将从列表中删除。
实际: 整个列表被删除,减去数组中的最后一项。

提前感谢您的任何投入!

144894 次浏览

I think this code will do

let targetIndex = list.findIndex((each) => {each.name == e.target.name});
list.splice(targetIndex-1, 1);

We need to check name value inside object so use findIndex instead. then cut the object start from target index to 1 array after target index.

Codepen

From your comment your problem came from another part.

Change this view section

    return (
<>
<span onClick={() => handleRemoveItem(item) }>x </span>
<span>{item.name}</span>
</>
)}

change function handleRemoveItem format

const handleRemoveItem = item => {
list.splice(list.indexOf(item)-1, 1)
updateList(list);
}

This is because both slice and splice return an array containing the removed elements.

You need to apply a splice to the array, and then update the state using the method provided by the hook

const handleRemoveItem = e => {
const newArr = [...list];
newArr.splice(newArr.findIndex(item => item.name === e.target.name), 1)
updateList(newArr)
}

You can use Array.filter to do this in a one-liner:

const handleRemoveItem = name => {
updateList(list.filter(item => item.name !== name))
}

Eta: you'll also need to pass the name of your item in your onClick handler:

{list.map(item => {
return (
<>
<span onClick={() =>handleRemoveItem(item.name)}>x </span>
<span>{item.name}</span>
</>
)}

First of all, the span element with the click event needs to have a name property otherwise, there will be no name to find within the e.target. With that said, e.target.name is reserved for form elements (input, select, etc). So to actually tap into the name property you'll have to use e.target.getAttribute("name")

Additionally, because you have an array of objects, it would not be effective to use list.indexOf(e.target.name) since that is looking for a string when you are iterating over objects. That's like saying find "dog" within [{}, {}, {}]

Lastly, array.slice() returns a new array starting with the item at the index you passed to it. So if you clicked the last-item, you would only be getting back the last item.

Try something like this instead using .filter(): codesandbox

import React, { useState } from "react";
import ReactDOM from "react-dom";


import "./styles.css";


const App = () => {
const defaultList = [
{ name: "ItemOne" },
{ name: "ItemTwo" },
{ name: "ItemThree" }
];


const [list, updateList] = useState(defaultList);


const handleRemoveItem = (e) => {
const name = e.target.getAttribute("name")
updateList(list.filter(item => item.name !== name));
};


return (
<div>
{list.map(item => {
return (
<>
<span name={item.name} onClick={handleRemoveItem}>
x
</span>
<span>{item.name}</span>
</>
);
})}
</div>
);
};


const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
const defaultList = [
{ name: "ItemOne" },
{ name: "ItemTwo" },
{ name: "ItemThree" }
]


const [list, updateList] = useState(defaultList);


const handleRemoveItem = idx => {
// assigning the list to temp variable
const temp = [...list];


// removing the element using splice
temp.splice(idx, 1);


// updating the list
updateList(temp);
}


return (
{list.map((item, idx) => (
<div key={idx}>
<button onClick={() => handleRemoveItem(idx)}>x </button>
<span>{item.name}</span>
</div>
))}


)

Small improvement in my opinion to the best answer so far

import React, { useState } from "react";
import ReactDOM from "react-dom";


import "./styles.css";


const App = () => {
const defaultList = [
{ name: "ItemOne" },
{ name: "ItemTwo" },
{ name: "ItemThree" }
];


const [list, updateList] = useState(defaultList);


const handleRemoveItem = (item) => {
updateList(list.filter(item => item.name !== name));
};


return (
<div>
{list.map(item => {
return (
<>
<span onClick={()=>{handleRemoveItem(item)}}>
x
</span>
<span>{item.name}</span>
</>
);
})}
</div>
);
};


const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Instead of giving a name attribute we just send it to the handle function

Redundant one liner - would not recommend as hard to test / type / expand / repeat / reason with

 <button onClick={() => setList(list.slice(item.id - 1))}

A version without exports:

 const handleDeleteItem = id => {
const remainingItems = list.slice(id - 1)
setList(remainingItems);
}

However I would consider expanding the structure of your logic differently by using helper functions in another file.

With that in mind, I made one example for filter and another for slice. I personally like the slice option in this particular use-case as it makes it easy to reason with. Apparently, it is also slightly more performant on larger lists if scaling (see references).

If using slice, always use slice not splice unless you have good reason not to do so as it adheres to a functional style (pure functions with no side effects)

// use slice instead of splice (slice creates a shallow copy, i.e., 'mutates' )
export const excludeItemFromArray = (idx, array) => array.slice(idx-1)


// alternatively, you could use filter (also a shallow copy)
export const filterItemFromArray = (idx, array) => array.filter(item => item.idx !== idx)

Example (with both options filter and slice options as imports)

import {excludeItemFromArray, filterItemFromArray} from 'utils/arrayHelpers.js'


const exampleList = [
{ id: 1, name: "ItemOne" },
{ id: 2, name: "ItemTwo" },
{ id: 3, name: "ItemThree" }
]


const [list, setList] = useState(exampleList);


const handleDeleteItem = id => {
  

//excluding the item (returning mutated list with excluded item)
const remainingItems = excludeItemFromArray(id, list)


//alternatively, filter item (returning mutated list with filtered out item)
const remainingItems = filterItemFromArray(id, list)


// updating the list state
setList(remainingItems);
}


return (
{list.map((item) => (
<div key={item.id}>
<button onClick={() => handleDeleteItem(item.id)}>x</button>
<span>{item.name}</span>
</div>
))}
)

References:

Using this pattern, the array does not jump, but we take the previous data and create new data and return it.

 const [list, updateList] = useState([
{ name: "ItemOne" },
{ name: "ItemTwo" },
{ name: "ItemThree" }
]);


updateList((prev) => {
return [
...prev.filter((item, i) => item.name !== 'ItemTwo')
]
})