簡體   English   中英

從狀態中刪除鍵(Redux Reducer)

[英]Delete key from state (Redux Reducer)

我在 Redux 中有一個狀態,目前呈現如下:

點擊前:

{0: {
    open: false,
    negation: false,
    close: false
    },
1: {
    open: false,
    negation: false,
    close: false,
    bool: "and"
    }
}

點擊后:

{0: {
    open: false,
    negation: false,
    close: false
    },
1: {}
}

我想完全刪除密鑰 1(通常是 [action.id])。

目前reducer中的cases有:

case 'HANDLE_INCREASE_CHANGE':
  return {
    ...state,
    index: state.index + 1,
    [state.index + 1]: {
      open:false,
      negation: false,
      close: false,
      bool: 'and'
    }
  }
case 'HANDLE_DECREASE_CHANGE':
  return {
    ...state,
    index: state.index - 1,
    [state.index]: {}
  }

錯誤的部分是:

[state.index]: {}

你能幫我嗎? 多謝!

您應該只能調用delete state[action.id] 盡管在 reducer 函數中,您應該首先獲取狀態的副本,從中刪除,然后返回復制的版本。

case: 'HANDLE_DECREASE_CHANGE':
  const next = {...state}
  delete next[action.id]
  return next

您正在為狀態對象設置新屬性,要刪除則需要使用delete 請記住先復制當前狀態。

case: 'HANDLE_DECREASE_CHANGE':
  let nextState = {...state}
  delete nextState[propToDelete]
  return nextState

我相信最好有一個元素數組,而不是直接將屬性設置為狀態對象。

const iniitalState = {
 index: 0,
 elements: []
}

case 'HANDLE_INCREASE_CHANGE': {
  state.elements.push({
    open:false,
    negation: false,
    close: false,
    bool: 'and'
  })
  return {...state, index: state.index + 1, elements: [...state.elements] }
}
case 'HANDLE_DECREASE_CHANGE': {
  let newElements = [...state.elements]
  newElements.splice(action.indexToRemove, 1) // Removes Element

  return {...state, index: state.index - 1, elements: [...newElements] }
}

刪除要刪除的密鑰:

const resultingState = {...state, index: state.index - 1}
delete resultingState[state.index]
return resultingState

或使用其余參數將其提取出來:

const {...extractedState, [state.index]: ignored} = state
return {...extractedState, index: state.index - 1}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM