As far as I can see, the only way to do it is to manually call store.update() in the script after making changes to the store. Is this correct?
这几乎是正确的。update
接收一个传递当前值并期望下一个值的函数。如果您在外部管理您的状态,然后将其传递到商店,请调用set
.
const myNewValue = doStuff(oldValue);
store.set(myNewValue);
对比
store.update(oldValue => doStuff(oldValue));
直接修改存储值(如storeValue.property = 1
)不会触发更新,您必须明确更新存储以使 Svelte 使变量无效。我还建议使用 store 中的方法来包装这些操作,这将帮助您跟踪代码变大时从何处更新的内容。
商店.js:
const _store = writable(initialValue);
function doASpecificModification(foo) {
_store.update(oldValue => { ... });
}
export const store = {
subscribe: _store.subscribe,
doASpecificModification
};
Would doing manual updates be less performant than what Svelte does automatically?
如果通过“自动”您的意思是$store = newValue
语法: That is desugared to a store.set(newValue)
,所以如果没有区别。此外,Svelte 只会重新渲染您订阅商店的部分,因此性能不应该成为问题(另请参阅下一节)。
My app needs to handle a pretty big nested store, with hundreds of branches. In the answer linked above, it is proposed to create a nested store, with branches wrapped in their own stores. Would having hundreds of (nested) stores significantly increase the memory footprint of the app compared to just using a single store?
关于性能:最好使更新更细化,或者通过将分支包装在他们自己的商店中,或者通过拥有一个大商店但选择商店的切片,如果他们不会触发更新部分没有改变(派生商店会帮助你)。如果这些分支彼此不相关,那么我建议将它们拆分(也是为了避免出现大块;我不喜欢 Redux 风格的保持一切在一个对象中)。内存占用不是这里的一个因素。