Svelte 使用编译器��构建您的代码,从而优化渲染。默认情况下,组件仅运行一次,除非它们在您的标记中被引用。为了能够对选项的更改做出反应,您需要使用 store。
在下面的示例中,refetchInterval 选项从变量 intervalMs 设置,该变量绑定到输入字段。但是,由于查询无法对 intervalMs 的更改做出反应,因此当输入值更改时,refetchInterval 不会更改。
<script lang="ts">
import { createQuery } from '@tanstack/svelte-query'
const endpoint = 'http://localhost: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 = 'http://localhost: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 转换为可写存储。然后可以将查询选项转换为派生存储,该存储将以真正的响应式传递给函数。
<script lang="ts">
import { derived, writable } from 'svelte/store'
import { createQuery } from '@tanstack/svelte-query'
const endpoint = 'http://localhost: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 = 'http://localhost: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} />