Реагировать на объект Redux Pu sh во вложенном массиве - PullRequest
0 голосов
/ 15 января 2020

Как вывести sh новое сообщение в массив соединений от редуктора? Я пытался найти правильное соединение по индексу, а затем до pu sh, но не могу приступить к работе. Схема соединений, например:

_id: 3213213,
messages:[...]

Схема сообщений, например:

_id: 123213,
author: '12312321',
body: 'Hi!'

Поэтому нужно найти правильное соединение из массива соединений, а затем до pu sh это в сообщениях массив внутри этого соединения

Код проблемы:

const messagesReducer = (state = [], action) => {
  switch (action.type) {
    case RECIEVE_CONNECTIONS:
      return action.payload;
    case UPDATE_MESSAGES:
      let index = state.findIndex(
      connection => connection._id === action.update.id
      );
      return [...state, state[index].messages.concat(action.update.message)];
   default:
    return state;
   }
};

export default messagesReducer;

Ответы [ 3 ]

1 голос
/ 15 января 2020

Вы фактически не обновляете состояние с помощью этой строки:

return [...state, state[index].messages.concat(action.update.message)];

Вы фактически портите свое состояние Redux, так как state представляет собой список соединений, и здесь вы включаете объединенный список messages.

Вот пример, который сохраняет ваше состояние относительно неизменным (если вы хотите полную неизменность, вам также необходимо клонировать все существующие соединения / сообщения, в этом примере я просто копирую массив)

let index = state.findIndex(
  connection => connection._id === action.update.id
);
const conn = state[index];
const messages = [ ...conn.messages, action.update.message ];
const newState = state.slice();
newState[index] = { ...conn, messages };
return newState;
0 голосов
/ 15 января 2020

Хорошо, я думаю, что понял. Может быть немного многословно, но я думаю, что вы поймете это лучше так. Это также полностью неизменным.

const messageToAdd = {
  _id: "xxx",
  body: "new message",
  author: "bar"
};

const index = state.findIndex(
  connection => connection._id === action.update.id
);

const connectionToUpdate = {
  ...state.slice(index, index + 1)[0]
};

const updatedMessagesArr = [
  ...connectionToUpdate.messages,
  messageToAdd
];

const updatedConnection = {
  ...connectionToUpdate,
  messages: updatedMessagesArr
};

return = [
  ...state.slice(0, index),
  updatedConnection,
  ...state.slice(index + 1)
];
0 голосов
/ 15 января 2020
const messagesReducer = (state = [], action) => {
  switch (action.type) {
    case RECIEVE_CONNECTIONS:
      return action.payload;
    case UPDATE_MESSAGES:
      // identify the index to update
      const index = state.findIndex(
        connection => connection._id === action.update.id
      );

      // create the new list of messages for the connection
      const messages = state[index].messages.concat(action.update.message)

      // modify the connection at index without modifying state
      const modifiedConnection = Object.assign({}, state[index], { messages });

      // replace the connection at index with the modified connection containing the new message
      return Object.assign([], state, { [index]: modifiedConnection });

   default:
    return state;
   }
};

Вы были близки, но вы добавляли в список подключений, когда вы действительно хотели добавить его во вложенный список сообщений для определенного c подключения.

...