简体   繁体   中英

update value inside array object

I only want to replace the name with the new name being typed in from the user. I'm using react redux typescript and its proving to be quite difficult. All the passed in arguments work, the newName and index , I just need to update the array object then return it with only the name in the index object changed.

My code:

Action:

export const updateName = (newName: string, index: number) => (
  dispatch: (arg0: { type?: string; newName: string; index: number }) => any
) => {
  dispatch({
    type: UPDATE_NAME,
    newName,
    index
  });
};

Reducer:

case UPDATE_NAME:
      return {
        ...state
        items[action.index].name: action.newName,

      };

State looks like this:

items: Array(50)
0: {id: "1d0b1095-f0b4-4881-8d5e-74c86d5beee2", name: "A Ipsum Debitis", participants: {…},
1: {id: "7384a574-1592-484e-9404-e876bf45410c", name: "Distinctio Blanditiis Voluptatibus Ut", participants: {…},

Along with shallow copying the state object, you need to shallow copy any nested state that is being updated as well, ie state.items and the specific array element that is being updated.

case UPDATE_NAME:
  return {
    ...state,
    items: state.items.map((el, i) => i === action.index ? {
      ...el,
      name: action.newName,
    } : el),
  };

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