简体   繁体   中英

Why doesn't the spread operator add properties to my array?

I'm working with a React useState variable. I have an array of objects that has 18 objects at this top level. I'm trying to update the object at the 14th index and then return the remaining objects after it. At first I was directly mutating the state by pushing my changes to it like so:

 setFormWizard(wizard => {
    wizard.controls[14].trash = true;
    return ({
      ...wizard,
      wizard: wizard.controls[14].group.push(...newSection.slice(0, 5)),
    });
  });

This works, but I'm told this isn't good practice because React may not catch the update if you push directly to the state in certain cases. So now I'm trying to use the spread operator instead.

What's happening is the first 14 objects are returning. The object I'm modifying is returning, but the rest of the objects that come after the 14th index are not returning. What am I doing wrong?

setFormWizard(wizard => {
  const subjectControls = wizard.controls[14]
  const groups = [...controls.group, ...subjectAddressCopy.slice(0, 5)]
  return ({
    ...wizard,
    controls: [
      ...wizard.controls.splice(0,14), // keep first 14 entries 
      {
        ...subjectControls,
        group: groups,
        trash: true
      } // modify the 15th entry
        ...wizard.controls.splice(15) // this doesn't return the remaining controls
      ],
  });
});

您可能想使用slice从索引 15 向上返回所有内容。

bcz splice changes in actual array you need to use slice

 const arr = [1, 2, 3, 4] arr.splice(0,2) console.log('splice change in array so actual value of arr is :', arr) const arr1 = [1,2,3,4,5] // it will take slice(start, end) but end not included in return value const cutSection = arr1.slice(1, 3); console.log('portion of array', cutSection)

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