简体   繁体   中英

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

I have an object like this

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

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

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.

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:

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

  c.splice(index,1)

  return { ...obj, c }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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