【问题标题】:Variable change doesn't render in the view变量更改不会在视图中呈现
【发布时间】:2023-01-13 00:43:15
【问题描述】:

如果上述行的唯一标识符在 rows 数组中,则以下代码的目的是显示一行。为什么 Svelte 仅在几次点击后才以一种看似随机的方式更新视图?

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

        let rows = [
            {"name": "Alex", "id": "0"},
            {"name": "Steve", "id": "1"},
            {"name": "Mike", "id": "2"},
        ]; 
    
    let expandedRows = [];
    
    function toggleExpandRows(row_id_to_toggle) {
            console.log("Row to toggle:", row_id_to_toggle)
            console.log(expandedRows);
      if (expandedRows.includes(row_id_to_toggle)) {
                console.log(expandedRows, "includes", row_id_to_toggle)
        expandedRows = expandedRows.filter(expanded_row_id => expanded_row_id !== row_id_to_toggle)
      } else {
        expandedRows.push(row_id_to_toggle);
      }
    }

</script>

<div class="overflow-x-auto w-full">
  <table class="table table-compact w-full">
    <thead>
      <tr>
        <th></th>
        <th>Name</th>
      </tr>
    </thead>
    <tbody>
      {#each rows as row (row.id)}
        <tr>
          <td>
            <button class="btn btn-xs" on:click={()=>toggleExpandRows(row.id)}>+/-</button>
          </td>
          <td class="min-w-[3rem] ">{row.name}</td>
        </tr>
            row.id: {JSON.stringify(row.id)}
        {#if expandedRows.includes(row.id)}
          <tr>
            <td colspan="2">-</td>
          </tr>
        {/if}

      {/each}
    </tbody>
  </table>
  Expanded: {JSON.stringify(expandedRows)}
</div>

REPL

【问题讨论】:

    标签: state render svelte


    【解决方案1】:

    除了expandedRows.push(row_id_to_toggle),你还应该分配expandedRows,这样 Svelte 就会知道它已经改变了。
    你可以试试:

    .
    .
    .
    else {
      expandedRows.push(row_id_to_toggle);
      expandedRows = expandedRows
    }
    

    【讨论】:

      【解决方案2】:

      反应性基于赋值,这就是为什么对于数组你也经常看到这种模式而不是push

      array = [...array, item];
      

      【讨论】:

      • 谢谢你的解释!我将能够在 1 分钟内接受答案。您是否愿意探索一下为什么 Svelte 仍会更新视图,但不是立即更新(通常在点击十几次之后)?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-10
      • 1970-01-01
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      • 2013-11-30
      • 1970-01-01
      相关资源
      最近更新 更多