这是我的状态
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] 删除。
我来说两句