1

Прошу мне объяснить. У меня есть:

const [dialogs, setDialogs] = useState([
  {
    chat_id: 0,
    messages: [
      {
        chat_id: 0,
        text: "test1"
      },
      {
        chat_id: 0,
        text: "test2"
      }
    ]
  }
])

Как мне вставить ещё один объект в массив messages, через setDialogs?

2
  • Напрямую никак. Вытащить значение dialogs, взять messages, запушить туда значение, а потом через setDialogs обновить состояние dialogs
    – SwaD
    31 окт 2022 в 11:43
  • А теперь тоже самое, только кодом 31 окт 2022 в 11:45

1 ответ 1

3
const [dialogs, setDialogs] = useState([
  {
    chat_id: 0,
    messages: [
      {
        chat_id: 0,
        text: "test1"
      },
      {
        chat_id: 0,
        text: "test2"
      }
    ]
  }
]);

// ...

setDialogs(p => {
    const copy = [...p]; // shallow copy
    copy[0].messages.push(newMessage);
    return copy;
});
0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.