简体   繁体   中英

Error with spread operation in array. TS1005: ',' expected. TypeScript

I cannot figure out what I missed on line row.sections[SECTION_ID . It always show me a typo error ','...

FAQ: sections - is an array with objects inside. In this case I'm trying modify the specific object of the sections founded by custom flag SECTION_ID.

PS

I also tried to put row.sections[SECTION_ID] inside an extra brackets [] , but unfortunately it does not help... Any solutions?

  rows: state.rows.map(
    row =>
      row.ID === action.rowID
        ? {
            ...row,
            sections: [
              ...row.sections,
              row.sections[SECTION_ID]: { // error is here
                ...row.sections[SECTION_ID],
                data: {
                  ...// some data
                }
              }
            ]
          }
        : row
  )

You cannot mutate some element inside array by spread operation in such way. Using this approach you'll jus add a new, mutated element to the same array each time. So, it you want to make it right, you need to use the map iterator instead:

rows: state.mymaps.rows.map(
    row =>
      row.ID === action.rowID
        ? {
            ...row,
            sections: row.sections.map(
              (section, index) =>
                index === JOIN_SECTION_ID
                  ? {
                      ...section,
                      data: {
                        ...section.data
                      }
                   } : section
             )
          } : row
)

If you're trying to replace an element at a certain index of the array without mutating the array, you can make a shallow copy of the array, and then set the value at that index. For example:

state.rows.map((row) => {
  if (rowID !== action.rowID) {
    return row;
  }
  const sectionCopy = [...row.sections];
  sectionCopy[SECTION_ID] = {
    ...row.sections[SECTION_ID],
    data: {
      // some data
    },
  };
  return {
    ...row,
    sections: sectionCopy,
  };
});

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