Sapper/Svelte - 如何定期获取
Sapper/Svelte - How to fetch periodically
我如何使用 Sapper 定期获取数据?
这是正确的方法吗?
//src/routes/fetch_on_this_page.svelte
<script>
setInterval(async () => {
//fetch here
}, 3000);
</script>
<script>
import { onMount, onDestroy } from "svelte";
async function fetchData() {
//Fetch
}
const interval = setInterval(async () => {
fetchData();
}, 3000);
onMount(async () => {
fetchData();
});
onDestroy(() => clearInterval(interval));
</script>
最简洁的方法是在内部完成所有操作 onMount
:
<script>
import { onMount } from 'svelte';
onMount(() => {
async function fetchData() {...}
const interval = setInterval(fetchData, 3000);
fetchData();
return () => clearInterval(interval));
});
</script>
除了创建更少的组件级变量外,onMount
代码不会 运行 在服务器端呈现期间,因此涉及的工作更少。如果您需要在多个组件中执行此操作,您还可以将其包装到自定义生命周期函数中:
// poll.js
import { onMount } from 'svelte';
export function poll(fn, ms) {
onMount(() => {
const interval = setInterval(fn, ms);
fn();
return () => clearInterval(interval));
});
}
<script>
import { poll } from './poll.js';
poll(async function fetchData() {
// implementation goes here
}, 3000);
</script>
我如何使用 Sapper 定期获取数据?
这是正确的方法吗?
//src/routes/fetch_on_this_page.svelte
<script>
setInterval(async () => {
//fetch here
}, 3000);
</script>
<script>
import { onMount, onDestroy } from "svelte";
async function fetchData() {
//Fetch
}
const interval = setInterval(async () => {
fetchData();
}, 3000);
onMount(async () => {
fetchData();
});
onDestroy(() => clearInterval(interval));
</script>
最简洁的方法是在内部完成所有操作 onMount
:
<script>
import { onMount } from 'svelte';
onMount(() => {
async function fetchData() {...}
const interval = setInterval(fetchData, 3000);
fetchData();
return () => clearInterval(interval));
});
</script>
除了创建更少的组件级变量外,onMount
代码不会 运行 在服务器端呈现期间,因此涉及的工作更少。如果您需要在多个组件中执行此操作,您还可以将其包装到自定义生命周期函数中:
// poll.js
import { onMount } from 'svelte';
export function poll(fn, ms) {
onMount(() => {
const interval = setInterval(fn, ms);
fn();
return () => clearInterval(interval));
});
}
<script>
import { poll } from './poll.js';
poll(async function fetchData() {
// implementation goes here
}, 3000);
</script>