使用钩子从数组中删除对象(useState) [英] Removing object from array using hooks (useState)

查看:190
本文介绍了使用钩子从数组中删除对象(useState)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我尝试使用 updateList(list.slice(list.indexOf(e.target.name, 1))).这将删除数组中除最后一项之外的所有内容,我不确定为什么.

const defaultList = [{名称:ItemOne"},{名称:项目二"},{名称:ItemThree"}]const [list, updateList] = useState(defaultList);const handleRemoveItem = e =>{updateList(list.slice(list.indexOf(e.target.name, 1)))}返回 ({list.map(item => {返回 (<><span onClick={handleRemoveItem}>x </span><span>{item.name}</span></>)}})

预期:点击的项目将从列表中删除.
ACTUAL:删除整个列表,减去数组中的最后一项.

提前感谢您的任何意见!

解决方案

首先,带有点击事件的 span 元素需要有一个 name 属性,否则,e.target 中将找不到名称.话虽如此,e.target.name 是为表单元素(输入、选择等)保留的.因此,要实际使用 name 属性,您必须使用 e.target.getAttribute("name")

另外,因为你有一个对象数组,所以使用 list.indexOf(e.target.name) 是无效的,因为它正在寻找一个 string> 当您迭代对象时.这就像在 [{}, {}, {}]

中找到dog"

最后,array.slice() 返回一个新数组从您传递给它的索引处的项目开始.因此,如果您点击最后一项,您将只能返回最后一项.

使用 .filter() 尝试类似的操作:codesandbox

import React, { useState } from "react";从react-dom"导入 ReactDOM;导入./styles.css";const App = () =>{const defaultList = [{名称:ItemOne"},{名称:项目二"},{名称:项目三"}];const [list, updateList] = useState(defaultList);const handleRemoveItem = (e) =>{const name = e.target.getAttribute("name")updateList(list.filter(item => item.name !== name));};返回 (<div>{list.map(item => {返回 (<><span name={item.name} onClick={handleRemoveItem}>X</span><span>{item.name}</span></>);})}

);};const rootElement = document.getElementById("root");ReactDOM.render(, rootElement);

I have an array of objects. I need to add a function to remove an object from my array without using the "this" keyword.

I tried using updateList(list.slice(list.indexOf(e.target.name, 1))). This removes everything but the last item in the array and I'm not certain why.

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

)

EXPECTED: The clicked item will be removed from the list.
ACTUAL: The entire list gets removed, minus the last item in the array.

Thanks in advance for any input!

解决方案

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

这篇关于使用钩子从数组中删除对象(useState)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆