이것은 나의 상태
this.state = {
notification: [{
from: {
id: someid,
name: somename
},
message: [somemessage]
},
{..},
{..},
]
}
이제 someid 에서 새 메시지를 받으면 해당 새 메시지를 someid의 메시지 배열 로 푸시해야합니다.
다른 방식으로 메시지를 보내려고했지만 효과가 없었습니다.
이런 식으로 시도했지만 새 메시지를 메시지 배열 로 푸시 할 수 없습니다.
if (this.state.notification) {
for (let q = 0; q < this.state.notification.length; q++) {
if (
this.state.notification[q] &&
this.state.notification[q].from &&
this.state.notification[q].from.id === r.from.id
) {
this.setState({
notification: [
...this.state.notification[q].messages,
this.state.notification[q].messages.push(r.message),
],
});
return console.log(this.state.notification[q].messages)
}
}
} else {
this.setState({
notification: [{
from: r.from,
messages: [r.message]
}, ]
});
return console.log(JSON.stringify(this.state.notification));
}
우선, 상태를 2D 배열로 구성하는 것은 좋은 생각이 아니라고 생각합니다. 하지만 당신은 이것을 시도 할 수 있습니다
const pushMessage = (someId, someMessage) => {
this.setState({
notifications: this.state.notifications.map((notification) => {
if (notification.from.id === someId) {
return {
...notification,
messages: [...notification.messages, someMessage],
};
}
return notification;
}),
});
};
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다