我有这个减速器:
<select id="product" class="form-control" name="product">
<option value="-1">-----</option>
<option value="0">Cat</option>
<option value="1">Dog</option>
<option value="2">Parrot</option>
<option value="3">Hamster</option>
</select>
我想将action.payload添加到messages数组的末尾。问题是:当我尝试将密钥放入有效负载时:
import { GET_CHAT, ADD_MESSAGE } from '../actions';
export default function (state = null, action) {
switch (action.type) {
case GET_CHAT:
return { ...state, [action.meta.id]: action.payload.data };
case ADD_MESSAGE:
console.log(state[action.meta.convId].chat.messages)
return {
...state,
[action.meta.convId]: {
...state[action.meta.convId],
chat: {
...state[action.meta.convId].chat,
messages: {
...state[action.meta.convId].chat.messages,
action.payload
}
}
}
};
default:
return state;
}
}
消息不再是一个数组,而是成为一个对象。所以我不能用map()循环它了。而redux不会让我直接将有效载荷推送到阵列,似乎我必须把钥匙...... 任何帮助将不胜感激,谢谢:)
答案 0 :(得分:2)
如果您希望您的消息始终是一个数组,那么您的reducer应该如下所示:
import { GET_CHAT, ADD_MESSAGE } from '../actions';
export default function (state = null, action) {
switch (action.type) {
case GET_CHAT:
return { ...state, [action.meta.id]: action.payload.data };
case ADD_MESSAGE:
console.log(state[action.meta.convId].chat.messages)
return {
...state,
[action.meta.convId]: {
...state[action.meta.convId],
chat: {
...state[action.meta.convId].chat,
messages: [ //USE SQUARE BRACKETS INSTEAD
...state[action.meta.convId].chat.messages,
action.payload
]
}
}
};
default:
return state;
}
}