3

我正在构建一个简单的应用程序,它可以根据内容的状态展开和折叠内容部分。基本上,如果collapse = false,则添加一个类,如果为true,则添加一个不同的类。

我将 Next.js 与 Redux 一起使用并遇到了问题。我想根据传递动作的参数更新状态。它没有更新状态,我不确定为什么或更好的选择是什么。任何澄清都会很棒!

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

currentName 变量导致状态不更新的问题。我希望能够动态地更改每个部分的状态,这就是为什么我认为我可以像这样拥有一个变量和更新状态。

看来您不能对键/值对中的键使用变量。为什么是这样?动态更新状态的替代方法是什么?

4

2 回答 2

3

那是因为 JavaScript 知道您想要创建一个名为currentName的键,而不是具有变量值的键currentName。为了做你想做的事,你必须currentName用括号括起来:

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

所以它会明白关键是什么currentName

于 2017-12-24T21:41:51.373 回答
0

也对:

return Object.assign({}, state, {
  [currentName]: Object.assign({}, state[currentName], {
    id: currentId,
    collapse: true
  })
})
于 2017-12-24T21:52:00.240 回答