Updating state in reducer using variables

旧时模样 提交于 2021-02-09 10:32:56

问题


I'm build a simple app that expands and collapses sections of content based on their state. Basically, if collapse = false, add a class and if it's true, add a different class.

I'm using Next.js with Redux and running into an issue. I'd like to update the state based on an argument the action is passed. It's not updating the state and I'm not sure why or what the better alternative would be. Any clarification would be great!

// DEFAULT STATE    
const defaultState = {
  membership: 'none',
  sectionMembership: {
    id: 1,
    currentName: 'Membership',
    nextName: 'General',
    collapse: false
  },
  sectionGeneral: {
    id: 2,
    prevName: 'Membership',
    currentName: 'General',
    nextName: 'Royalties',
    collapse: true
  }
}

// ACTION TYPES
export const actionTypes = {
  SET_MEMBERSHIP: 'SET_MEMBERSHIP',
  MOVE_FORWARDS: 'MOVE_FORWARDS',
  MOVE_BACKWARDS: 'MOVE_BACKWARDS'
}

// ACTION
export const moveForwards = (currentSection) => dispatch => {
  return dispatch({ type: actionTypes.MOVE_FORWARDS, currentSection })
}

// REDUCERS
export const reducer = (state = defaultState, action) => {
  switch (action.type) {
      case actionTypes.SET_MEMBERSHIP:
        return Object.assign({}, state, {
          membership: action.membershipType
        })
      case actionTypes.MOVE_FORWARDS:
        const currentId = action.currentSection.id
        const currentName = "section" + action.currentSection.currentName    
        return Object.assign({}, state, {
          currentName: {
            id: currentId,
            collapse: true
          }
        })
    default: return state
  }
}

The currentName variable is causing an issue for the state to not update. I want to be able to dynamically change each sections state, which is why I thought I'd be able have a variable and update state like this.

It seems you can't use a variable for the key in the key/value pair. Why is this? What's an alternative to dynamically updating state?


回答1:


That is because JavaScript understands that you want to create a key named currentName not a key with the value of the variable currentName. In order to do what you want, you have to wrap currentName in brackets:

return Object.assign({}, state, {
          [currentName]: {
            id: currentId,
            collapse: true
          }
        })

So it will understand that the key will be whatever currentName is.




回答2:


It also right:

return Object.assign({}, state, {
  [currentName]: Object.assign({}, state[currentName], {
    id: currentId,
    collapse: true
  })
})


来源:https://stackoverflow.com/questions/47964037/updating-state-in-reducer-using-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!