我对Redux和React有一个奇怪的问题。状态正确更改,在reducer中,我也获得了正确的新状态,但是更改后,组件将不会重新呈现。
case 'READ_MESSAGE_FROM_USER':
{
let copyChat = Object.assign({}, { state: state })
let chatHistory = copyChat.state
const userIndex = chatHistory.findIndex(item => item.chatThreadId === action.mes.threadId)
if (userIndex != -1) {
if (chatHistory[userIndex].conversation) {
let messages = [...chatHistory[userIndex].conversation]
const msgIndex = messages.findIndex(item => item.id === action.mes.messageId)
console.log(chatHistory[userIndex].conversation[msgIndex], "READ_MESSAGE_FROM_USER")
if (msgIndex != -1) {
chatHistory[userIndex].conversation[msgIndex].readDate = action.mes.date
}
}
}
return chatHistory
}
答案 0 :(得分:0)
redux toolkit随附的immer随附的最新redux模板npx create-react-app my-app --template redux
要设置状态而不使用浸入式,您可以执行以下操作:
case 'READ_MESSAGE_FROM_USER': {
return state.map((historyItem) =>
historyItem.chatThreadId !== action.mes.threadId
? historyItem
: {
...historyItem,
conversation: historyItem.conversation.map(
(conversationItem) =>
conversationItem.id !== action.mes.messageId
? conversationItem
: {
...conversationItem,
readDate: action.mes.date,
}
),
}
);
}