如何将 Svelte 存储与树状嵌套对象一起使用?从这个答案:
注意:绑定仅在相同变量时才有效。也就是说,您不能将绑定变量放入中间变量中,并让 Svelte 继续跟踪此绑定。
这以及我自己的测试似乎意味着无法从 Svelte 组件外部的脚本反应性地更新嵌套存储(更新存储并更新状态)。据我所知,唯一的方法是在store.update()对商店进行更改后手动调用脚本。它是否正确?
我正在考虑重构我的代码:我的主要组件的代码变得太笨拙,我想引入更多组件,并且可能将.js文件中的状态更新函数保留在组件之外,以实现可重用性。
关于性能的一些问题:
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);
Run Code Online (Sandbox Code Playgroud)
与
store.update(oldValue => doStuff(oldValue));
Run Code Online (Sandbox Code Playgroud)
直接修改存储值(如storeValue.property = 1)不会触发更新,您必须显式更新 Svelte 的存储以使变量无效。我还建议用存储中的方法包装这些操作,这将帮助您跟踪当代码变大时从哪里更新的内容。
商店.js:
const _store = writable(initialValue);
function doASpecificModification(foo) {
_store.update(oldValue => { ... });
}
export const store = {
subscribe: _store.subscribe,
doASpecificModification
};
Run Code Online (Sandbox Code Playgroud)
Would doing manual updates be less performant than what Svelte does automatically?
如果“自动”指的是$store = newValue语法: That is desgared 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 风格的将所有内容保留在一个对象中)。内存占用不是这里的一个因素。
| 归档时间: |
|
| 查看次数: |
1570 次 |
| 最近记录: |