在 Svelte 中,如何在从数组中删除对象后重新渲染视图?

How can I re-render a view after deleting an object from an array, in Svelte?

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

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 here.

问题

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

我该怎么做?

要让 svelte 接受对国家/地区数组的更改,您需要创建数组的新引用。为此,您可以使用 Array.filter 方法。

<script>
    let countries = [
     { code: "AF", name: "Afghanistan" },
     { code: "AL", name: "Albania" },
     { code: "IL", name: "Israel" }
    ];
    
    function deleteCountry(code) {
        countries = countries.filter(c => c.code !== code)
    }
</script>

<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 on:click="{() => deleteCountry(c.code)}" 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>

您也可以直接使用国家代码作为 deleteCountry 方法的参数。

添加

countries = countries;

在这一行之后

countries.splice(itemIdx,1);

因为 reactivity/rerendering/UI update 仅在分配后标记。