【发布时间】:2022-01-04 04:19:22
【问题描述】:
我试图将对象插入特定对象(即对象列表)。下面是代码。
import MESSAGES from '../actions/Messages';
import update from 'immutability-helper';
const chatReducer = (state = [], { type, payload }) => {
switch (type) {
case CHATS:
// state = [...state, payload];
// return state;
return state, payload;
case MESSAGES:
let index = state.findIndex(
chat => chat.chatId === payload.chatId);
const conn = state[index];
const messages = [...conn.messages, payload];
const newState = state.slice();
newState[index] = { ...conn, messages };
//console.log("ne ", newState)
return newState;
default:
return state
};
};
export default chatReducer;
这里只是根据 id 找到对象并将有效负载插入到无法正常工作的消息数组中。
【问题讨论】:
-
当状态为空数组时,您的
index将是未定义的 -
也
return state, payload;似乎不正确。 -
@SaeedShamloo 是的,状态是一个对象值数组。我刚刚做了一个调试。
-
console.log("ne ", newState)的输出是什么?这是你预期的结果吗? -
不,它没有打印出来。
标签: reactjs redux react-redux