【问题标题】:Should a spread operator be used when updating an object with svelte/store update method?使用 svelte/store 更新方法更新对象时是否应该使用扩展运算符?
【发布时间】:2020-03-28 15:28:24
【问题描述】:

我正在创建一个使用对象来存储我的数据的商店。

我可以使用扩展运算符更新商店,但我也可以不使用扩展运算符更新它。

Svelte 是否像 React 一样,我应该在更新对象状态之前使用扩展运算符创建一个新对象,这样我就不会改变原始对象?

withSpreadOperator()withoutSpreadOperator()... 这就是问题所在。

//stores.js

import { writable } from "svelte/store";

export const counts = writable({ n: 0 });
//App.js

<script>
  import { count } from "./stores.js";

  function withSpreadOperator() {
    count.update(o => {
      let x = { ...o };
      x.n++;
      return x;
    });
  }

  function withoutSpreadOperator() {
    count.update(o => {
      o.n++;
      return o;
    });
  }
</script>

<h1>The count is {$count.n}</h1>
<button on:click="{withSpreadOperator}">+</button>
<button on:click="{withoutSpreadOperator}">+</button>

【问题讨论】:

    标签: svelte svelte-store


    【解决方案1】:

    你也可以,Svelte 不介意。这真的取决于你喜欢哪种风格。

    【讨论】:

      猜你喜欢
      • 2018-09-04
      • 2021-12-28
      • 2017-06-13
      • 2017-06-12
      • 2017-11-15
      • 1970-01-01
      • 1970-01-01
      • 2018-06-25
      相关资源
      最近更新 更多