Редуктор: добавление элемента во вложенный массив на основе индекса - PullRequest
0 голосов
/ 02 июня 2018

У меня такая ситуация ...

const INITIAL_STATE = {chat: []}

Затем я устанавливаю чат и включаю эти данные:

[
 {
  "otherParty":"aaaaa",
  "thread":[
     {
        "a":1,
        "b":2,
        "c":3
     },
     {
        "d":4,
        "e":5,
        "f":6
     }
  ]
 },
 {
  "otherParty":"bbbb",
  "thread":[
     {
        "a":1,
        "b":2,
        "c":3
     },
     {
        "d":4,
        "e":5,
        "f":6
     }
  ]
 },
 {
  "otherParty":"cccc",
  "thread":[
     {
        "a":1,
        "b":2,
        "c":3
     },
     {
        "d":4,
        "e":5,
        "f":6
     }
  ]
 }
]

Мне нужно добавить новый элемент в массив [1]. Что-то вроде {g: 7, h: 8, i: 9} - Другими словами: я хотел бы указать индекс массива иДобавить новую тему.

Как архивировать это?

export const addNewThread = (obj, index) => {
  return {
    type: ADD_NEW_THREAD,
    payload: {
        thread: obj,
        index: index
    }
  }
}

и редуктор ... (мне нужно заполнить ????)

const INITIAL_STATE = {
  chat: []
}
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
    case ADD_NEW_THREAD:
        return {
            ...state,
            chat: ?????
        }

  }
  return state
}

1 Ответ

0 голосов
/ 02 июня 2018

как то так

const INITIAL_STATE = {
  chat: []
}
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
    case ADD_NEW_THREAD:
        const chat = state.chat.slice();
        const thread = chat[action.index].thread.concat(action.thread);
        chat.splice(action.index, 1, thread);
        return {
            chat
        };

  }
  return state
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...