当用户从一个页面导航到另一个页面时,SvelteKit 会调用你的 load
函数,但前提是它认为某些内容已发生更改。
¥When the user navigates from one page to another, SvelteKit calls your load
functions, but only if it thinks something has changed.
在此示例中,在时区之间导航会导致 src/routes/[...timezone]/+page.js
中的 load
函数重新运行,因为 params.timezone
无效。但 src/routes/+layout.js
中的 load
函数不会重新运行,因为就 SvelteKit 而言,它并没有因导航而失效。
¥In this example, navigating between timezones causes the load
function in src/routes/[...timezone]/+page.js
to re-run because params.timezone
is invalid. But the load
function in src/routes/+layout.js
does not re-run, because as far as SvelteKit is concerned it wasn’t invalidated by the navigation.
我们可以通过使用 invalidate(...)
函数手动使其无效来解决这个问题,该函数接受一个 URL 并重新运行任何依赖于它的 load
函数。因为 src/routes/+layout.js
中的 load
函数调用 fetch('/api/now')
,所以它依赖于 /api/now
。
¥We can fix that by manually invalidating it using the invalidate(...)
function, which takes a URL and re-runs any load
functions that depend on it. Because the load
function in src/routes/+layout.js
calls fetch('/api/now')
, it depends on /api/now
.
在 src/routes/[...timezone]/+page.svelte
中,添加每秒调用一次 invalidate('/api/now')
的 onMount
回调:
¥In src/routes/[...timezone]/+page.svelte
, add an onMount
callback that calls invalidate('/api/now')
once a second:
<script>
import { onMount } from 'svelte';
import { invalidate } from '$app/navigation';
let { data } = $props();
onMount(() => {
const interval = setInterval(() => {
invalidate('/api/now');
}, 1000);
return () => {
clearInterval(interval);
};
});
</script>
<h1>
{new Intl.DateTimeFormat([], {
timeStyle: 'full',
timeZone: data.timezone
}).format(new Date(data.now))}
</h1>
<script lang="ts">
import { onMount } from 'svelte';
import { invalidate } from '$app/navigation';
let { data } = $props();
onMount(() => {
const interval = setInterval(() => {
invalidate('/api/now');
}, 1000);
return () => {
clearInterval(interval);
};
});
</script>
<h1>
{new Intl.DateTimeFormat([], {
timeStyle: 'full',
timeZone: data.timezone
}).format(new Date(data.now))}
</h1>
你还可以将函数传递给
invalidate
,以防你想要根据模式而不是特定 URL 使其无效¥[!NOTE] You can also pass a function to
invalidate
, in case you want to invalidate based on a pattern and not specific URLs