无法弄清楚如何正确地将元素插入数组中,该数组位于数组内的对象内部。以下是我的结构默认数据的示例:
const defaultState = {
myinbox: [
{
owner: 'John Lennon',
owner_id: 1,
read: true,
messages: [
{
_id: 1,
text: 'When will you be home?',
createdAt: new Date(Date.UTC(2017, 10, 11, 11, 20, 0)),
user: {
_id: 1,
name: 'John Lennon'
}
}
...
我想在收到入站邮件时添加另一条消息。这就是我的reducer的代码片段:
const inboxReducer = (state = defaultState, action) => {
switch (action.type) {
case 'ADD_INBOUND_MESSAGE':
return {
...state,
myinbox: [
state.myinbox[action.payload.index]: {
...state.myinbox[action.payload.index],
messages: [
...state.myinbox[action.payload.index].messages,
action.payload.msg
]
}
...state.myinbox,
]
}
default:
return state
}
}
父“owner”的索引作为有效负载内的索引传递,新消息在有效负载中为msg。
我无法弄清楚如何在不改变原始状态的情况下编写此缩减器。
答案 0 :(得分:0)
这可以通过 Immer
完成 const { index, msg } = action.payload;
return produce(state, (draftState) => {
draftState.myinbox[index].messages.push(msg);
});