【问题标题】:SVELTE calling await function when value returned by function changes on template当函数返回的值在模板上发生变化时,SVELTE 调用 await 函数
【发布时间】:2021-03-11 10:15:46
【问题描述】:

我不明白为什么 SVELTE 在函数返回的值发生更改时调用 {#await} 块中指定的函数。

我做了一个小例子:

https://svelte.dev/repl/a962314974eb4a07bd98ecb1c9ccb66c?version=3.35.0

简而言之:

{#await getList() then alist}
    {#each alist as item}
    <div>
        {item.state}
        <div class="button" on:click={()=>item.state=!item.state}>Toggle it!</div>
    </div>
    {/each}
{/await}

函数getList() 每次单击“按钮” div 以切换函数返回的对象上的值时都会被调用。我不明白为什么。

有人可以启发我吗?

谢谢!

【问题讨论】:

    标签: svelte


    【解决方案1】:

    我认为这是因为当状态改变时整个组件被重新渲染,因此getList()被再次调用,因为它在渲染代码中。

    更好的解决方案可能是找到如何使用immutable 避免整个重新渲染,但这里有一种方法可以实现这一点:

    <script>
        let list = [
            { state: true}, { state: true}, { state: true},{ state: true}
        ]
        let counter = 0;
        async function getList(){
            counter++;
            return Promise.resolve(list);
        }
        const promise = getList()
    </script>
    
    Times GetList called: {counter}
    
    {#await promise then alist}
        {#each alist as item}
        <div>
            {item.state}
            <div class="button" on:click={()=>item.state=!item.state}>Toggle it!</div>
        </div>
        {/each}
    {/await}
    

    【讨论】:

    • 谢谢!我修好了我的等待
    • 我也会深入研究“不可变”,我在文档中看到了它,但我不明白它的确切含义。现在我看得更清楚了。
    【解决方案2】:

    状态更改不会(通常)导致整个组件重新渲染,这毕竟是 Svelte 的基本原则。您可以通过在 await 中添加第二个计数器和一个按钮来尝试:

    {#await getList() then alist}
      <button on:click={() => counter2++}>Clicked {counter2}</button>
      ...
    

    单击此按钮将增加 counter2 而不会再次触发 getList

    这里的问题似乎是由于您正在直接编辑异步操作的结果,这会以某种方式重新触发所述操作。考虑到其他答案有效,这一定与它是一个函数调用有关。

    解决此问题的另一种方法是将每个循环的内部移动到它自己的组件中:

    {#await getList() then alist}
      {#each alist as item}
        <Child {...item} />
      {/each}
    {/await}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 2014-03-15
      • 2023-02-08
      • 1970-01-01
      相关资源
      最近更新 更多