简体   繁体   English

在 state 数组上反应 array.splice 不能正确更新 dom?

[英]React array.splice on state array does not update dom properly?

I have an object like this我有一个像这样的 object

const obj =  {
      a:'something',
      b:'something else',
      c : [
        {
          a:'something',
          b:'something else',
        },
        {
          a:'something2',
          b:'something else2',
        },
      ]
    }

when i call the function to remove one element from the array c like this当我像这样调用 function 从数组 c 中删除一个元素时

//where index is 0 for example
const removeItem = index => setObj({...obj,c:obj.c.splice(index,1)})

the item gets removed from the array and the page however on the page the element left that i mapped from c have the values of c[0] but if i console.log(obj.c) i get this该项目从数组和页面中删除,但是在页面上,我从 c 映射的左侧元素具有 c[0] 的值,但如果我 console.log(obj.c) 我得到这个

const obj =  {
      a:'something',
      b:'something else',
      c : [
        {
          a:'something2',
          b:'something else2',
        },
      ]
    }

which is actually what i want but it's not reflected on the page..... what am i doing wrong?这实际上是我想要的,但它没有反映在页面上.....我做错了什么?

When Array.splice() removes items, it mutates the original array, and returns an array of the removed items.Array.splice()删除项目时,它会改变原始数组,并返回已删除项目的数组。

Use another method to remove the item, such as filter, which returns a new array without the item:使用另一种方法删除项目,例如过滤器,它返回一个没有项目的新数组:

const removeItem = index => setObj(o => ({ 
  ...o, 
  c: obj.c.filter((_, i) => i !== index)
}))

Or clone the array with array spread, and then splice it:或者用array spread克隆数组,然后拼接:

const removeItem = index => setObj(o => {
  const c = [...o.c]

  c.splice(index,1)

  return { ...obj, c }
})

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

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