【问题标题】:angular ngrx store update array item if id matches如果 id 匹配,角度 ngrx 存储更新数组项
【发布时间】:2021-10-10 21:51:15
【问题描述】:

我有很多电话。它们有不同的关键字,并且 call 的 id 是 call_id。数组开始时为空。如果数组为空或没有带有来电ID的呼叫,则必须将呼叫添加到状态中的呼叫数组。否则,当 state 中的数组有一个带有传入 id 的调用时,它将更新匹配的调用。现在 initialState.calls[] 还是空的

 export interface Call {
  timestamp: number;
  call_id: string;
  keywords: Keyword[];
}

 export const initialState: KeywordsModel = {
   version: '',
   calls: [],
   isOpen: false,
   lastUpdatedOn: Date.now()
 };

 export const reducer = createReducer(
   initialState,
   on(KeywordsWebSocketActions.messageReceived, (state, { message, timeReceived }) => ({
     ...state,
     ...message,
     lastUpdatedOn: timeReceived
   })),
   on(KeywordsWebSocketActions.keywordsPageOpened, state => ({ ...state, isOpen: true })),
   on(KeywordsWebSocketActions.messageCallReceived, (state, { call }) => ({ ...state, calls: (state.calls.map((existCall: Call) => (existCall.call_id === call.call_id) ? state.calls[existCall.call_id] : [...state.calls, call])),
  }),
  
  ))
 
 export function reducerFactory(state: KeywordsModel | null, actions: Action) {
   return reducer(state, actions);
 }

使用 map() 的 messageCallReceived 完成后,STATE 保持为空 {}

请指教。

【问题讨论】:

    标签: angular typescript ngrx store


    【解决方案1】:

    我不太确定您想要实现什么,但最有可能正确的代码是这样的:

    state.calls.map((existCall: Call) => (existCall.call_id === call.call_id) ? call: existCall)
    

    这应该只更新数组中的一项

    编辑:更新的完整逻辑,如果没有更新 - 推送新项目

    on(KeywordsWebSocketActions.messageCallReceived, (state, { call }) => {
       let wasUpdated = false;
       const newCalls = state.calls.map(c => {
          if( c.call_id == call.call_id) {
             wasUpdated = true;
             return call;
          } else {
             return c;
          }
       })
       if(!wasUpdated){
          newCalls.push(call);
       }
       return {
         ...state,
         calls: newCalls,
       }
    })
    

    【讨论】:

    • 我有很多电话。它们有不同的关键字,并且 call 的 id 是 call_id。数组开始时为空。如果数组为空或没有带有来电ID的呼叫,则必须将呼叫添加到状态中的呼叫数组。否则,当 state 中的数组有一个带有传入 id 的调用时,它将更新匹配的调用。现在 initialState.calls[] 仍然是空的 :(
    • 请给我更多的说明。
    • 啊,我明白了。此代码将仅替换相应的项目。如果没有找到,我将使用有关如何添加项目的逻辑来更新答案
    猜你喜欢
    • 2018-05-14
    • 2019-04-05
    • 2018-06-30
    • 2019-05-01
    • 1970-01-01
    • 2020-07-31
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多