如何更新 reducer 中 observable 的 属性 的值?

How Can I update the value of property of an observable in reducer?

我想在开始活动时更新与特定用户的所有 mydirect 消息的状态, 我如何通过仅过滤此用户和尚未看到的消息来更新此 属性...谢谢

 //----------State Message---------------//
   //----------State Message---------------//
 on(directMessagesAction.seenMyRecievedMessage, (state, { payload }) => {
    const messages = [...state.allDirectMessages];
    for (let m of messages) {
      if (
        m.messageModel.from.userName == payload.userName &&
        m.messageModel.isSeen == false
      ) {
        m.messageModel.isSeen = true;
      }
    }

    return { ...state, allDirectMessages: messages };
  }),


这是directMessage的模型

import { MessageViewModel } from "./messageViewModel";
import { OnlineUserModel } from "./onlineUserModel";
export class DirectMessage {
  public fromOnlineUser: OnlineUserModel | null = {
    userName: "",
    email: "",
    firstname: "",
    profilePic: "",
    isProfileComplete: "",
    isActive: "",
  };
  public messages = "";

  public messageModel: MessageViewModel = {
    content: "",
    timestamp: "",
    from: null,
    to: null,
    avatar: "",
    attachement: "",
    fileSize: "",
    fileNameSaved: "",
    isSeen: false,
    isSeenDate: "",
  };
  ////-------- ***** try with message Oject *****------/////
}

问题是您无法更改方法传递给您的状态。是read-only。因此,您对 state.allDirectMessages 的更改会导致错误。

Cannot assign to read only property 'messageModel' of object '[object Object]' ... allDirectMessage array of DirectMessage

最简单的解决方案是复制您要更改的部分,然后覆盖它。

on(directMessagesAction.seenMyRecievedMessage, (state, { payload }) => {
    const messages = [...state.allDirectMessages]
    for (let m of messages) {
        if (m.messageModel.from.userName == payload.userName && m.messageModel.isSeen == false) {
            m.messageModel.isSeen = true;
        }
    }

    return { ...state, allDirectMessages: messages };
  }),

编辑:
我对逻辑的复制

const messages: Message[] = [
    { sender: 'Me', isSeen: false },
    { sender: 'You', isSeen: false }
]

// map solution
const updated = messages.map(m => ({ ...m, isSeen: true } as Message))
console.log(updated);

// loop solution
for (let m of messages) {
    m.isSeen = true;
}
console.log(messages);