从状态删除密钥(Redux Reducer)

时间:2020-01-24 13:44:13

标签: javascript redux

我在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])。

目前在减速器中的情况是:

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]: {}

能帮我吗?非常感谢!

3 个答案:

答案 0 :(得分:4)

您应该只能致电delete state[action.id]。尽管在使用reducer函数时,您应该首先获取状态的副本,然后从状态中删除,然后返回复制的版本。

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

答案 1 :(得分:2)

您正在为状态对象设置新属性,要删除该属性,则需要使用delete。记住要先复制当前状态。

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

我相信最好有一个元素数组,而不是直接将属性设置为sate对象。

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] }
}

答案 2 :(得分:0)

删除您要删除的密钥:

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}