Svelte Store & Temp 变量,无需覆盖



我有存储数组的对象。Stores可以从一个带有"完成"one_answers"取消"按钮的弹出式组件中访问。我的目标是仅在用户点击"完成"按钮时更新商店。如果弹出窗口关闭或点击"取消"按钮,我就不想更新商店。我认为我可以使用一个局部变量来分配Store的值,但即使在更新局部变量时,它也会更新Store。商店应该这样运作吗?

这是弹出组件

<script>
import Button from "./Button.svelte";
import CategorySectionStore from '../stores/categorySectionStore';
import CategoryListStore from '../stores/categoryListStore';
import AccountSectionStore from '../stores/accountSectionStore';
import AccountListStore from '../stores/accountListStore';
import PayeeListStore from '../stores/payeeListStore';
let categorySections = [...$CategorySectionStore];
let categoryLists = [...$CategoryListStore];
let accountSections = [...$AccountSectionStore];
let accountLists = [...$AccountListStore];
let payeeLists = [...$PayeeListStore];
export let togglePopup = () => {};
export let filter;
const toggleCategoryGroup = (groupID) => {
for (let list of categoryLists) {
// console.log(list)
// console.log('gid: ' + groupID)
if (list.Id === groupID) {
list.Checked = !list.Checked;
}
}
}

</script>
<div class="popup {filter}">
<p class="title">{filter}</p>
<div class="selection">
<ul>
<li>Select All</li>
<li>Select None</li>
</ul>
</div>
<div class="list">
{#if filter === 'Categories'}
<ul>
{#each categorySections as catSection}
<li class="section">
<input type=checkbox group={catSection.Name} value={catSection.Name} checked={catSection.Checked} on:click={() => toggleCategoryGroup(catSection.Id)}>{catSection.Name}
</li>
{#each categoryLists as catList}
{#if catList.Id === catSection.Id}
<li class="section-item"><input type=checkbox group={catSection.Name} value={catList.subName} checked={catList.Checked}>{catList.subName}</li>
{/if}
{/each}
{/each}
</ul>
{:else if filter === 'Accounts'}
<ul>
{#each accountSections as accountSection}
<li class="section"><input type=checkbox group={accountSection.Name} value={accountSection.Name} bind:checked={accountSection.Checked}>{accountSection.Name}</li>
{#each accountLists as accountList}
{#if accountList.Type === accountSection.Name}
<li class="section-item"><input type=checkbox group={accountSection.Name} value={accountList.Name} bind:checked={accountList.Checked}>{accountList.Name}</li>
{/if}
{/each}
{/each}
</ul>
{:else}
<ul>
{#each payeeLists as payeeList}
<li class="section-item"><input type=checkbox group="payeeSection" value={payeeList.Name} checked={payeeList.Checked}>{payeeList.Name}</li>
{/each}
</ul>
{/if}
</div>
<div class="buttons">
<Button type="secondary" on:click={togglePopup}>Cancel</Button>
<Button>Done</Button>
</div>
</div>

这里是商店。它们都是一样的,只是名字不同。

import { writable } from 'svelte/store';
export const CategorySectionStore = writable([]);
export default CategorySectionStore;

这不是由于存储的性质,而是由于JavaScript本身的工作方式。当您将数组从存储区扩展到本地数组时,您只是将引用扩展到实际对象。因此数组中的元素仍然指向内存中的相同位置。

如果你的对象数组是"浅的"(也就是说没有嵌套的对象),你可以用地图和扩展技术来代替:

const myarray = otherarray.map(item => ({ ...item }))

这将创建具有相同属性的全新对象。但正如前面提到的,如果其中一个属性是它自己的对象,它将再次成为引用。

最新更新