问题描述
我正在构建一个简单的应用程序,可以根据内容的状态展开和折叠内容部分.基本上,如果collapse = false,则添加一个类,如果为true,则添加一个不同的类.
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.
我在 Redux 中使用 Next.js 并遇到了问题.我想根据传递动作的参数更新状态.它没有更新状态,我不确定为什么或更好的选择是什么.任何澄清都会很棒!
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
}
}
currentName 变量导致状态无法更新的问题.我希望能够动态更改每个部分的状态,这就是为什么我认为我可以拥有一个变量并像这样更新状态.
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?
推荐答案
那是因为 JavaScript 明白你想要创建一个名为 currentName
的键,而不是一个带有变量 值的键当前名称
.为了做你想做的事,你必须将 currentName
括在方括号中:
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
}
})
所以它会理解密钥将是 currentName
是什么.
So it will understand that the key will be whatever currentName
is.
这篇关于使用变量更新减速器中的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!