gpt4 book ai didi

svelte - 更新 Svelte 可写数组存储的正确方法是什么?

转载 作者:行者123 更新时间:2023-12-05 01:23:24 24 4
gpt4 key购买 nike

更新 $orderItems = writable([]) Svelte 可写数组存储的正确方法是什么(或者如果两者都正确则有区别)?我们假设 result 是我想在 $orderItems 末尾推送的新项目。

orderItems.update(items => ([...items, result]))

$orderItems = [...$orderItems, result]

最佳答案

两者都是正确的,另一种选择是

$orderItems.push(result)
$orderItems = $orderItems

orderItems.update(items => {
items.push(result)
return items
})

区别在于$语法只能在组件内部使用,所以.svelte文件。来自 the docs

Any time you have a reference to a store, you can access its value inside a component by prefixing it with the $ character. This causes Svelte to declare the prefixed variable, subscribe to the store at component initialization and unsubscribe when appropriate.

如果您想从 .js 文件修改商店,这只能通过 .set()/.update()

关于svelte - 更新 Svelte 可写数组存储的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72379987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com