gpt4 book ai didi

svelte - 使用 Svelte 派生存储从多个存储数据创建单个状态对象

转载 作者:行者123 更新时间:2023-12-05 05:43:34 42 4
gpt4 key购买 nike

我尝试实现一个自定义的 Svelte 商店,它允许我在订阅页面上“抛出”一个单一的状态对象。这是我准备的示例代码:

import { derived, writable } from 'svelte/store'
import SomeOtherStore from '$stores/otherstore.js'
import { page } from '$app/stores'

const initialState = {
loading: true,
items: [],
param: null,
}

const createPageStore = () => {
// Create main store since derived store cannot be updated, set initial state
const mainStore = writable(initialState)
const { update } = mainStore

// instantiate other store needed to construct page state
const someOtherStore = SomeOtherStore()

function someKindOfFunctionModifyingState() {
// Need to update the state of items derived from SomeOtherStore, but the items do not exist here as the state was not propagated to the main store
update(state => {
return {
...state,
items: state.items.map(stringItem => stringItem.capitalizeFirst())
}
})
}

// combine stores in order to construct page state
const { subscribe } = derived([mainStore, page, someOtherStore], ([$mainStore, $page, $someOtherStore]) => {
const { someItems, loading } = $someOtherStore

return {
...$mainStore,
loading: $mainStore.loading || loading,
param: $page.url.searchParams.get('param'),
items: someItems,
}
})

return {
someKindOfFunctionModifyingState,
// return subscribe method from derived store
subscribe,
}
}

let instance

export default function PageStore() {
return instance ?? (instance = createPageStore())
}

ma​​inStore 是我认为我能够做到这一点的方式,因为派生 stores 无法更新

如您所见,我需要使用 SomeOtherStore 提供的数据在我的状态对象中构建示例项目。

我遇到的问题是,当我需要更新这些项目的状态时,我无法执行此操作,因为 mainStore 中的 items 数组为空,而我没有这样做知道如何将生成的派生状态传递给 mainStore

如果我尝试从派生存储函数中将最终派生状态设置为 mainStore,显然不足为奇,这会导致循环。

<script>
import PageStore from '$stores/pageStore.js'

const store = PageStore()

</script>


{#each $store.items as item}
<span>{item}</span>
{/each}
<button on:click={store.someKindOfFunctionModifyingState}>
Click to capitalize first letter
</button>

页面组件中的示例用法

TL;DR 基本上,我的需求是能够创建从多个商店组合的单个对象状态,并能够在例如发生点击事件时更新该状态。

我怎样才能做到这一点?

最佳答案

代替

 const { subscribe } = derived(...

 const combined = derived(...

这将允许 someKindOfFunctionModifyingState 函数使用 get效用。

import { get } from "svelte/store";

function someKindOfFunctionModifyingState() {
const $combined = get(combined);
mainStore.update(($mainStore) => ({
...$mainStore,
items: $combined.items.map(stringItem => stringItem.capitalizeFirst())
}))
}

使用 get 有一个小的性能开销,但是对于点击事件来说可以忽略不计

关于svelte - 使用 Svelte 派生存储从多个存储数据创建单个状态对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71797741/

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