每个组件都有一个生命周期,从创建时开始,到销毁时结束。 有一些函数允许你在生命周期的关键时刻运行代码。
英Every component has a lifecycle that starts when it is created, and ends when it is destroyed. There are a handful of functions that allow you to run code at key moments during that lifecycle.
你最常使用的是 onMount
,它在组件首次渲染到 DOM 后运行。 当我们需要在渲染后与 <canvas>
元素进行交互时,我们短暂地遇到了 earlier。
英The one you'll use most frequently is onMount
, which runs after the component is first rendered to the DOM. We briefly encountered it earlier when we needed to interact with a <canvas>
element after it had been rendered.
我们将添加一个 onMount
处理程序来通过网络加载一些数据:
英We'll add an onMount
handler that loads some data over the network:
<script>
import { onMount } from 'svelte';
let photos = [];
onMount(async () => {
const res = await fetch(`/tutorial/api/album`);
photos = await res.json();
});
</script>
由于服务器端渲染 (SSR),建议将
fetch
放在onMount
中,而不是放在<script>
的顶层。 除了onDestroy
之外,生命周期函数在 SSR 期间不会运行,这意味着我们可以避免在组件安装到 DOM 中后获取应延迟加载的数据。
必须在组件初始化时调用生命周期函数,以便将回调绑定到组件实例 — 不是(比如)在 setTimeout
中。
英Lifecycle functions must be called while the component is initialising so that the callback is bound to the component instance — not (say) in a setTimeout
.
如果 onMount
回调返回一个函数,则该函数将在组件被销毁时被调用。
英If the onMount
callback returns a function, that function will be called when the component is destroyed.