代码之家  ›  专栏  ›  技术社区  ›  Timmo

JS/ReactJS-分配新变量会更改原始变量

  •  0
  • Timmo  · 技术社区  · 6 年前

    var themes = [
      {
        id: 1,
        name: 'Light',
      },
      {
        id: 2,
        name: 'Dark',
      }
    ];
    

    我有个方法 React Component

      addTheme = (theme) => {
        const base = themes.find(t => t.name.toLowerCase() === theme.base.toLowerCase());
        var newTheme = base ? base : themes[0];
        console.log(newTheme);
        newTheme.id = themes[themes.length - 1].id + 1;
        newTheme.name = theme.name;
        themes.push(newTheme);
        console.log('themes:', themes);
      };
    

    我得到的问题是 newTheme 变量到 base 似乎覆盖了数组中的基对象。

    Midnight ,和 Dark

    logs

    3 回复  |  直到 6 年前
        1
  •  2
  •   Jordan Enev    6 年前

    你应该复制一个主题对象,因为 find 返回对对象的引用。

    你有两个选择- 浅的 复制对象。

    一。浅拷贝

    const newTheme = {...base ? base : themes[0]}
    

    2。深拷贝 (如果没有函数属性):

    JSON.parse(JSON.stringify(base ? base : themes[0]))
    

    How do I correctly clone a JavaScript object? .

        2
  •  1
  •   Dan Inactive    6 年前

    这个 find() array方法不会返回主题的副本,而是返回对它的引用,因此您实际上正在更改原始主题。

        3
  •  1
  •   UtkarshPramodGupta    6 年前

    使用 Object.assign()

    Object.assign({}, obj) 返回 obj 对象(请注意,不是深层克隆)。

    addTheme = (theme) => {
        const base = themes.find(t => t.name.toLowerCase() === theme.base.toLowerCase());
        var newTheme = base ? Object.assign({},base) : Object.assign({},themes[0]);
        console.log(newTheme);
        newTheme.id = themes[themes.length - 1].id + 1;
        newTheme.name = theme.name;
        themes.push(newTheme);
        console.log('themes:', themes);
    };