我试图将对象插入特定对象(即对象列表(。下面是代码。
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找到对象,并将有效负载插入消息数组,但这不起作用。
您必须进行两次检查
- 如果索引-1(未找到聊天id(:添加新的聊天对象
- 不要切片,它只会返回其余的项,索引将不匹配
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);
if (index !== -1) {
const conn = state[index];
const messages = [...conn.messages, payload];
const newState = [...state]; // use destructuring instead of slice
newState[index] = { ...conn, messages };
return newState;
}
return [
...state,
/* <add new chat object> */
]; // Do something if the chat doesn't exist
default:
return state;
}
};
我会回答我自己的问题,谢谢@Rahul Sharma你刚刚重定向了我。我更改了对象是因为我的应用程序要求。
import CHATS from '../actions/ChatMessages';
import MESSAGES from '../actions/Messages';
import SEARCH from '../actions/SearchUser';
const chatReducer = (state = {}, { type, payload }) => {
switch (type) {
case CHATS:
return { ...state, payload };
case MESSAGES:
let index = state.payload.chats.findIndex(
chat => chat.chatId === payload.chatId
);
let conn = state.payload.chats[index];
const msg = payload.msg;
conn.lastMsg = msg;
const messages = [...conn.messages, payload];
const newState = { ...state };
newState.payload.chats[index] = { ...conn, messages };
console.log("state ", newState);
return newState;
default:
return state
};
};
export default chatReducer;