有没有办法在 Svelte 中的 {#each} 块之后设置语句?

Is there a way to set a Statement after an {#each} Block in Svelte?

我是 Svelte 的新手,在完成本教程后构建此组件 (https://reactjs.org/docs/thinking-in-react.html) 以便更好地理解它。在第 2 步中,ProductTable class 中有一个部分,其中在每个循环之后有以下语句 lastCategory = product.category;。有没有一种方法可以在每个块之后写一个语句?以下是我目前的代码。

<script>
    import ProductCategoryRow from './ProductCategoryRow.svelte';
    import ProductRow from './ProductRow.svelte';

    export let products;

    let lastCategory = null;
</script>


<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
        {#each products as product}
            {#if product.category !== lastCategory}
                <ProductCategoryRow category={product.category} />
            {/if}
            <ProductRow product={product} />
            <!-- lastCategory = product.category (?) -->
        {/each}
    </tbody>
</table>

抱歉我的英语不好,提前致谢:)

你不能在 Svelte 中这样做。 相反,你会做一个简单的反向查找:

{#each products as product, i}
    {#if i !== 0 && product.category || products[i-1].lastCategory}
        <ProductCategoryRow category={product.category} />
    {/if}
        <ProductRow product={product} />
{/each}

(请注意,您也可以在 React 中执行此操作)

作为替代构造,您还可以使用中间组件并使用 <script context="module"> 在此处设置逻辑。

类似于:

<script>
  import { onDestroy } from 'svelte'
  import ProductRowWrapper, { resetLastCategory } from './ProductRowWrapper.svelte'

  export let products

  // make sure the last category is reset to an empty string when
  // the entire product list is unmounted, in order to have a clean
  // initialization when it is mounted again with a different set of products
  onDestroy(resetLastCategory)
</script>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody>
    {#each products as product}
      <ProductRowWrapper {product} />
    {/each}
  </tbody>
</table>
ProductRowWrapper.svelte

<script context="module">
  let lastCategory = ''

  export function resetLastCategory() {
    lastCategory = ''
  }
</script>

<script>
  import ProductCategoryRow from './ProductCategoryRow.svelte'
  import ProductRow from './ProductRow.svelte'

  export let product

  let displayCategory = product.category !== lastCategory

  lastCategory = product.category
</script>

{#if displayCategory}
  <ProductCategoryRow category={product.category} />
{/if}
<ProductRow {product} />