简体   繁体   English

Sapper/Svelte - 如何定期获取

[英]Sapper/Svelte - How to fetch periodically

How would I periodically fetch data using Sapper?我将如何使用 Sapper 定期获取数据?

Is this the correct way?这是正确的方法吗?

//src/routes/fetch_on_this_page.svelte

<script>
  setInterval(async () => {
    //fetch here
  }, 3000);
</script>

The neatest way to do this is to do it all inside onMount :最简洁的方法是在onMount内部完成所有操作:

<script>
  import { onMount } from 'svelte';

  onMount(() => {
    async function fetchData() {...}

    const interval = setInterval(fetchData, 3000);
    fetchData();

    return () => clearInterval(interval));
  });
</script>

Aside from creating fewer component-level variables, onMount code doesn't run in during server-side rendering, so involves less work.除了创建更少的组件级变量之外, onMount代码不会在服务器端渲染期间运行,因此涉及的工作更少。 If you needed to do this in multiple components you could also wrap this up into a custom lifecycle function:如果您需要在多个组件中执行此操作,您还可以将其包装到自定义生命周期 function 中:

// 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>
<script>
  import { onMount, onDestroy } from "svelte";

  async function fetchData() {
  //Fetch
  }

  const interval = setInterval(async () => {
    fetchData();
  }, 3000);

  onMount(async () => {
    fetchData();
  });

  onDestroy(() => clearInterval(interval));
</script>

https://svelte.dev/tutorial/ondestroy https://svelte.dev/tutorial/ondestroy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM