我有一个简单的操作来设置 n1 维度的状态 我的状态对象和 reducer 看起来像这样
const F2F = {
openF2F: false,
...
}
const initialState = {
showModal: false,
F2F,
...
}
export default function reducer(state=initialState, action) {
switch (action.type) {
case psActions.ON_CHANGE:
return {
...state,
[action.fieldName]: action.value
}
default:
return state
}
}
我有一个问题,如何使操作指向状态对象
export function onChangeDim(value, name, dimension) {
return {
type: psActions.ON_CHANGE,
fieldName: dimension[name],//Tried many things her
value: value
}
}
更新 现在我知道如何指向 F2F 对象
case psActions.ON_CHANGE_DIM:
return {
...state,
[action.dimension]: {
[action.fieldName]:action.value
}
}
但不知道如何在 F2F 内传递其余状态。因为现在当我设置一种状态时,里面只有一种状态 谁能帮我?
最佳答案
尝试以下 block 来解决您的嵌套状态问题。
如果您使用 babel transform-object-rest-spread ,看起来您就是这样。
return {
...state,
[action.dimension]: {
...state[action.dimension],
[action.fieldName]:action.value
}
}
Object.assign({}, state[action.dimensions], { ... })
也可以使用其他方式。
编辑:解决您的评论;
请查看 MDN 上有关 Object.assign() 的文档
The
Object.assign()
method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
因此,在此示例中:Object.assign({}, state[action.dimensions], { ... })
我们采用一个空对象{}
并将所有可枚举和自己属性从state[action.dimensions]
分配给它。然后,我们从 { ... }
中获取可枚举和自己的属性,并将它们应用到更新后的对象。
合并具有相同属性的对象
The properties are overwritten by other objects that have the same properties later in the parameters order
这就是当您使用 babel transform-object-rest-spread 时 ...object
被转换成的内容。插件。
深度克隆警告
For deep cloning, we need to use other alternatives because Object.assign() copies property values. If the source value is a reference to an object, it only copies that reference value.
关于javascript - 如何对多维对象使用 Redux actions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45339585/