Svelte Store赋值本地临时变量修改时原Store被同步更新问题求解
问题原因
这不是Svelte Store的异常机制,核心是JavaScript引用类型的浅拷贝特性导致的:
你使用[...$Store]的方式只做了数组层的浅拷贝,数组内部存储的对象仍然和原Store里的对象指向同一块内存地址,所以你修改本地变量里的对象属性时,原Store里的对应对象也会同步变更。
解决方案
1. 初始化本地临时变量时做深拷贝
把原来的浅拷贝写法替换为深拷贝,直接切断本地变量和原Store的引用关联,推荐用原生APIstructuredClone(现代浏览器、Node.js 17+均支持,适合处理普通对象、数组等常见类型):
// 修改前的浅拷贝写法 // let categorySections = [...$CategorySectionStore]; // 修改后的深拷贝写法 let categorySections = structuredClone($CategorySectionStore); let categoryLists = structuredClone($CategoryListStore); let accountSections = structuredClone($AccountSectionStore); let accountLists = structuredClone($AccountListStore); let payeeLists = structuredClone($PayeeListStore);
2. 仅在点击Done按钮时同步到Store
新增Done按钮的点击逻辑,确认提交时才把修改后的本地变量覆盖到原Store:
const handleDone = () => { CategorySectionStore.set(categorySections); CategoryListStore.set(categoryLists); AccountSectionStore.set(accountSections); AccountListStore.set(accountLists); PayeeListStore.set(payeeLists); togglePopup(); }
然后给按钮绑定事件:
<Button on:click={handleDone}>Done</Button>
点击Cancel或者直接关闭弹窗时不需要做任何额外处理,下次打开弹窗时会重新从Store拉取最新值做深拷贝,之前的临时修改会直接丢弃。
兼容说明
如果需要兼容不支持structuredClone的旧环境,你可以用符合业务场景的深拷贝实现,比如针对你当前都是纯数据对象数组的场景,也可以用JSON.parse(JSON.stringify(xxx))临时替代,注意该方式无法处理函数、Date、正则等特殊类型。
内容的提问来源于stack exchange,提问作者user1715916
相关产品推荐
相关产品推荐

