javascript - 如何对多维对象使用 Redux actions?

标签 javascript reactjs redux react-redux

我有一个简单的操作来设置 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/

相关文章:

javascript - ES6 - 使用 import 语句在类上声明原型(prototype)方法

reactjs - 如何更改 onClick,ionic v4 React 上的元素?

javascript - 我是否通过替换对象中的整个数组来改变我的 reducer 状态?

redux - 如何登录到 Redux 中的文件?

javascript - 使用 jquery load() 将内容添加到选项卡式导航中

javascript - 我可以找到 window.onclick() 函数何时被覆盖吗?

reactjs - 在 React 中使用跨度作为文本输入且内容可编辑

javascript - 预填充受控组件

javascript - 发生Redux状态更改时,组件不会更新

javascript - Object.assign 为什么以及如何提高 React 中的应用程序性能?