简体   繁体   中英

Updating and displaying counter variable value within an #each block

I'm having a tough time solving what seems to be a relatively simple problem. I'm being thrown off by svelte's reactivity feature.

Within an #each block, I need to update and display the value of an increasing "counter" after each iteration. Unfortunately passing in the counter variable updates all the iterations values to the latest count.

Is there a way to "bake" the value of the variable into each iteration instead of them only referencing the variable?

<!-- the console log shows the desired result instead of the "6" value for every iteration -->
<script>
    let arr = ["a","b","c","d","e","f"];
    let counter = 0
    let increment = ()=>{
        counter++
        console.log(counter)
        return ""
    }
    const getCount = counter
</script>

{#each arr as item,i}
<p>
    {item} -> {counter}
</p>
{increment()}
{/each}

<!-- I cannot use the "i"  since in my actual code I have #if blocks within the #each blocks which can either increment the counter or reset the counter.-->

Svelte REPL showing the issue.

Any ideas?

in increment change return to return counter ... then {item} -> {increment()} and remove that other {increment()}

So:

<script>
    let arr = ["a","b","c","d","e","f"];
    let counter = 0
    let increment = ()=>{
        counter++
        console.log(counter)
        return counter
    }
    const getCount = counter
</script>

{#each arr as item,i}
<p>
    {item} -> {increment()}
</p>
{/each}

Modifying state in an #each is not a good idea, as noted by Geoff Rich this can lead to unexpected behavior.

You should associate each item with the appropriate index when you generate your data and then simply bind to the property that contains said index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM