【问题标题】:Does svelte have built-in protection against updating a reactive variable in async operation when the component is unmounted卸载组件时,svelte 是否具有内置保护以防止在异步操作中更新反应变量
【发布时间】:2023-01-27 01:43:25
【问题描述】:

我的 App 组件是这样设置的。为简洁起见,仅显示相关代码。

// script
let view = 'products';

// markup
<sidebar/>
<view-container>
   {#if view === 'products'}
     <products />
   {:else if view === 'orders'}
     <orders />
   {/if}
<view-container>

products.svelte 中,我有一个 api 获取一些数据并为其分配一个反应变量。

//script
let data = [];
fetch(url).then(res => res.json()).then(json => {
  data = json; // just assume json is an array;
})

//markup
{#each data as entry (entry.id)}
  <product-card product_info={entry} />
{/each}

考虑到我可以使用 sidebar 非常快速地在 productsorders 视图之间切换。将会发生的是 fetch 调用会有点晚,并且对数据变量的赋值将在 products 组件被销毁之后进行。这是由图书馆本身干净地处理的吗?那些分配只是空操作是真正的错误吗?如果我们考虑通过在组件出现错误后设置状态来做出反应的类似场景。

我知道 onMountonDestroy 苗条的钩子。我很好奇这个场景。我无法从文档中找到关于此的答案。

【问题讨论】:

    标签: javascript reactive-programming svelte


    【解决方案1】:

    如果 svelte 确实支持这个,那么在他们的文档中不容易找到。

    但是,浏览器 fetch() API 确实允许 AbortSignal 对象实例,它允许您与给定的获取请求通信并在需要时中止它。

    Read more about implementing an AbortSignal instance on the MDN docs, here.

    希望这可以帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      • 2023-02-15
      • 1970-01-01
      • 2017-08-25
      • 2018-06-05
      • 1970-01-01
      相关资源
      最近更新 更多