简体   繁体   中英

How do I update array inside object in redux

I have an array I'm writing a code for redux now.

const initialState = [{ id: '1', title: '', description: '' }];

I would like to update that array like this

[{ id: '1', title: '', description: '' },{ id: '2', title: '', description: '' }];

and after copying I want to update the copy one of id to '2'

here is what I tried

    case COPY_QUESTION: {
      const copyQuestion = state.find(question => question.id === action.payload)
      copyQuestion?.id = (state.length + 1).toString()
      return [...state, copyQuestion];
    }

it didn't work for me. if I try to change id, the 0 index changes too at the same time. like this

[{ id: '2', title: '', description: '' },{ id: '2', title: '', description: '' }];

I would really appreciate your help thanks for reading this question.

Something like this should work:

const initialState = [{ id: '1', title: '', description: '' }];

const copyInitialState = [...initialState]

copyInitialState.push({ id: parseInt(copyInitialState[copyInitialState.length - 1].id, 10) + 1, title: '', description: '' })

//setState

copyInitialState is then equal to:

[
 {
  id:"1",
  title:"",
  description:""
 },
 {
  id:2,
  title:"",
  description:""
 }
]

JavaScript handels Objects by reference and therefore 'find' only returns the address in memory of the already existing object, which you then manipulate.

You have to clone your object first, eg using the spread operator (not for deep clones):

const originalQuestion = state.find(question => question.id === action.payload)
const copyQuestion = { ...originalQuestion }

Have a look at this SO question for more context and possibilities.

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