更新数组中对象的正确方法是什么?
What is the correct way of updating an object in an array?
我有一个对象数组,在我的代码中我列出了这些
{#each advances as tech}
<Advance tech={tech} addToCart={addToCart}/>
{/each}
添加到购物车函数更新对象上的变量:
const addToCart = (tech) => {
tech.Cart = true;
}
这不会触发反应,我应该怎么做?
一种方法是使用索引来引用列表中的项目
{#each advances as tech, index}
<Advance tech={tech} on:click={() => advances[index].cart = true}/>
{/each}
示例:https://svelte.dev/repl/70d4235faefd4f1b87ad6d359d02f05b?version=3
假设您想做的不仅仅是简单地切换一个标志,您还可以这样做:
const addToCart = (tech) => {
tech.Cart = true;
advances = advances;
}
这将强制阵列上的反应性触发器。
我有一个对象数组,在我的代码中我列出了这些
{#each advances as tech}
<Advance tech={tech} addToCart={addToCart}/>
{/each}
添加到购物车函数更新对象上的变量:
const addToCart = (tech) => {
tech.Cart = true;
}
这不会触发反应,我应该怎么做?
一种方法是使用索引来引用列表中的项目
{#each advances as tech, index}
<Advance tech={tech} on:click={() => advances[index].cart = true}/>
{/each}
示例:https://svelte.dev/repl/70d4235faefd4f1b87ad6d359d02f05b?version=3
假设您想做的不仅仅是简单地切换一个标志,您还可以这样做:
const addToCart = (tech) => {
tech.Cart = true;
advances = advances;
}
这将强制阵列上的反应性触发器。