首页 > 解决方案 > 如何在 Svelte 中从数组中删除对象后重新渲染视图?

问题描述

我正在开发一个小型 Svelte 应用程序,用于学习目的(我是 Svelte 新手)。该应用程序使用在视图中显示的对象数组作为 HTML 表格:

let countries = [
    { code: "AF", name: "Afghanistan" },
    { code: "AL", name: "Albania" },
    { code: "IL", name: "Israel" }
]; 

<table class="table table-bordered">
  <thead>
    <tr>
      <th>#</th>
      <th>Code</th>
      <th>Name</th>
      <th class="text-right">Actions</th>
    </tr>
  </thead>
  <tbody>
    {#if countries.length}
     {#each countries as c, index}  
      <tr>
       <td>{index+1}</td>
       <td>{c.code}</td>
       <td>{c.name}</td>
       <td class="text-right">
        <button data-code="{c.code}" on:click="{deleteCountry}" class="btn btn-sm btn-danger">Delete</button>
       </td>
      </tr>
     {/each}
    {:else}
    <tr>
      <td colspan="4">There are no countries</td>
    </tr>
    {/if}
  </tbody>
</table>

我正在以这种方式进行删除操作:

function deleteCountry(){
    let ccode = this.getAttribute('data-code');
    let itemIdx = countries.findIndex(x => x.code == ccode);
    countries.splice(itemIdx,1);
    console.log(countries);
}

这里有一个 REPL 。

问题

countries在更新数组(从中删除一个元素)后,我无法再次呈现表(视图)。

我怎么做?

标签: javascriptsveltesvelte-3svelte-2

解决方案


添加

countries = countries;

在这条线之后

countries.splice(itemIdx,1);

因为反应性/重新渲染/UI 更新仅在分配后标记。


推荐阅读