简体   繁体   English

ReactJS 从 state (对象数组)中删除项目

[英]ReactJS remove item from state (array of objects)

I am doing an E-shop template in ReactJS to practice, everything is done but I can't figure out what is the best way to remove one item from state in form of array with objects.我在 ReactJS 中做一个电子商店模板来练习,一切都完成了,但我不知道从 state 中删除一个项目的最佳方法是带对象的数组形式。

Here is an example of what I am trying to do:这是我正在尝试做的一个例子:

Defining my state:定义我的 state:

const [cartData, setCartData] = useState([])

Adding items to it:向其中添加项目:

const exampleFunction = (heading, price) => {
    setCartData([...cartData, {name: heading, price: price}])
}

All of this is working just fine so my state after adding some items looks like this:所有这些都工作得很好,所以我的 state 在添加一些项目后看起来像这样:

[{name: "White T-shirt", price: "$20"}, {name: "Red T-shirt", price: "$20"}]

Now my question is, if user clicks the delete button and I pass to my delete function the name parameter, how do I remove the one item with received name?现在我的问题是,如果用户单击删除按钮并且我将名称参数传递给我的删除 function,我如何删除收到名称的一项? Here is what I was trying to do but it didn't really work out:这是我试图做的,但它并没有真正奏效:

  const deleteItem = (name) => {
    var newList = []
    cartData.map(d => {
      if (d.name !== name) {
        newList.push(d.name)
      }
      return d
    })
    setCartData([])
    newList.map(item => {
      setCartData([...cartData, {name: item.name}])
    })
  } 

Like I said, I must've done it wrong because this is not doing the job for me.就像我说的,我一定是做错了,因为这对我没有用。 What is the best way to go about deleting one item from state? go 关于从 state 中删除一项的最佳方法是什么? (please don't try to repair my code if there is better/smarter solution) (如果有更好/更智能的解决方案,请不要尝试修复我的代码)

Thank you!谢谢!

This should remove the entry with the specified name from cardData :这应该从cardData中删除具有指定名称的条目:

const deleteItem = (name) => {
  const newCartData = cartData.filter((d) => d.name !== name);
  setCartData(newCartData);
};

What you want is the filter array prototype method.您想要的是filter数组原型方法。


  const deleteItem = (name) => {
    setCartData((state) => state.filter((item) => item.name !== name))
  } 

When using the current state value to update state, it's good practice to pass a callback function to setState .当使用当前 state 值更新 state 时,最好将回调 function 传递给setState

You need to use filter() method of array.您需要使用数组的filter()方法。 According to MDN web docs, the filter() method creates a new array with all elements that pass the test implemented by the provided function.根据 MDN web 文档,filter() 方法创建一个新数组,其中包含所有通过提供的 function 实现的测试的元素。

const deleteItem = (name) => {
    const newList = cartData.filter(d => d.name !== name);
    setCartData(newList);
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM