Svelte 使用编译器构建你的代码,从而优化渲染。默认情况下,组件只运行一次,除非它们在你的标记中被引用。为了能够对选项中的更改做出反应,你需要使用 stores。
在下面的示例中,refetchInterval 选项是从变量 intervalMs 设置的,该变量绑定到输入字段。但是,由于查询无法对 intervalMs 中的更改做出反应,因此当输入值更改时,refetchInterval 不会更改。
<script lang="ts">
import { createQuery } from '@tanstack/svelte-query'
const endpoint = 'https://:5173/api/data'
let intervalMs = 1000
const query = createQuery({
queryKey: ['refetch'],
queryFn: async () => await fetch(endpoint).then((r) => r.json()),
refetchInterval: intervalMs,
})
</script>
<input type="number" bind:value={intervalMs} />
<script lang="ts">
import { createQuery } from '@tanstack/svelte-query'
const endpoint = 'https://:5173/api/data'
let intervalMs = 1000
const query = createQuery({
queryKey: ['refetch'],
queryFn: async () => await fetch(endpoint).then((r) => r.json()),
refetchInterval: intervalMs,
})
</script>
<input type="number" bind:value={intervalMs} />
为了解决这个问题,我们可以将 intervalMs 转换为可写 store。然后可以将查询选项转换为派生 store,它将以真正的反应性传递给函数。
<script lang="ts">
import { derived, writable } from 'svelte/store'
import { createQuery } from '@tanstack/svelte-query'
const endpoint = 'https://:5173/api/data'
const intervalMs = writable(1000)
const query = createQuery(
derived(intervalMs, ($intervalMs) => ({
queryKey: ['refetch'],
queryFn: async () => await fetch(endpoint).then((r) => r.json()),
refetchInterval: $intervalMs,
})),
)
</script>
<input type="number" bind:value={$intervalMs} />
<script lang="ts">
import { derived, writable } from 'svelte/store'
import { createQuery } from '@tanstack/svelte-query'
const endpoint = 'https://:5173/api/data'
const intervalMs = writable(1000)
const query = createQuery(
derived(intervalMs, ($intervalMs) => ({
queryKey: ['refetch'],
queryFn: async () => await fetch(endpoint).then((r) => r.json()),
refetchInterval: $intervalMs,
})),
)
</script>
<input type="number" bind:value={$intervalMs} />