ngrx-默认值是否通过传播运算符覆盖? [英] ngrx- default values being overwritten through spread operator?

查看:74
本文介绍了ngrx-默认值是否通过传播运算符覆盖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个将状态树的一部分转换为视图模型的ngrx选择器.举一个简单的例子,在我的状态树中,我有一个manager数组.因此,我对状态树进行了以下设置,并查看了模型-

I am working on an ngrx selector that converts a section of the state tree into a view model. As a simple example, in my state tree I have an array of manager. Thus I have the following setup for my state tree, and view model-

export interface Manager {
    id: string,
    name: string
}

export interface AppState {
    managers: Manager[]
}

export interface ManagersVM {
    byId: {[key: string]: Manager},
    allIds: string[]
}

export const defaultManagersVM: ManagersVM {
    byId: {},
    allIds: []
};

然后在我的选择器中,我有:

Then in my selector, I have:

export const selectManagersVM = createSelector(selectManagers, (data) => {
    let mgrsVM: ManagersVM = { ...defaultManagersVM };
    for(let mgr of data.managers) {
        mgrsVM.byId[mgr.id] = mgr;
        mgrsVM.allIds.push(mgr.id);
    }
})

我遇到的问题是该行:

let mgrsVM: ManagersVM = { ...defaultManagersVM };

似乎没有复制defaultManagersVMs属性. (运行选择器后,defaultManagersVM的console.log显示它现在具有非空的byId和allIds).我的印象是,新定义的对象内的传播算子将创建一个副本,但这似乎是错误的.我该如何确保defaultManagersVM不会在选择器中发生变异.

seems to not be making a copy of defaultManagersVMs properties. (a console.log of defaultManagersVM after running the selector shows that it now has a non-empty byId and allIds). I was under the impression that the spread operator within a newly defined object would create a copy, but that appears to be wrong. How can I ensure that defaultManagersVM does not get mutated in my selector.

推荐答案

传播算子 Lodash ).

The spread operator does not make a deep copy of nested objects, JavaScript does not have this functionality by default. An option is to use an external library (I.e. Lodash, which supports deep cloning).

或者,如果您需要其他库未涵盖的某些特定功能,则可以编写自己的递归深度克隆功能.

Alternatively, you can write your own recursive deep cloning function, if you require some particular functionality that's not covered by other libraries.

这篇关于ngrx-默认值是否通过传播运算符覆盖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆