【发布时间】:2020-11-08 07:36:31
【问题描述】:
这是我的状态
this.state = {
notification: [{
from: {
id: someid,
name: somename
},
message: [somemessage]
},
{..},
{..},
]
}
现在,如果我从 someid 收到一条新消息,我必须将该新消息推送到 someid
的 message 数组中我尝试以不同的方式推送该消息,但没有任何效果
我尝试过这种方式,但我无法将新消息推送到 message 数组中
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));
}
【问题讨论】:
标签: javascript reactjs state setstate