首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在使用svelte/store update方法更新对象时,是否应该使用spread操作符?

在使用svelte/store update方法更新对象时,是否应该使用spread操作符?
EN

Stack Overflow用户
提问于 2019-12-03 21:31:52
回答 1查看 2.1K关注 0票数 4

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

我可以使用扩展操作符更新商店,但也可以不使用扩展操作符来更新它。

Svelte类似于React吗?在更新对象的状态之前,我应该使用spread操作符来创建一个新对象,这样我就不会对原始对象进行变异了吗?

withSpreadOperator()withoutSpreadOperator()..。那倒是一个问题。

代码语言:javascript
运行
复制
//stores.js

import { writable } from "svelte/store";

export const counts = writable({ n: 0 });
代码语言:javascript
运行
复制
//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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-04 01:44:58

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

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59165666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档