我将如何在苗条的反应中制作每个循环

互联网 行业动态 更新时间:2024-06-13 00:19:19

pla*_*ogo 5

通常,该{#each}语句是响应式运行的,并且如果变量messages更改,则应该更新。

但是,要让 Svelte 在数组中注册更新,您必须重新分配变量。

Svelte Docs 中的一般示例代码:

numbers = [] //TODO: We want a function that adds an item to the end of the array, that is the array Length + 1, so after a few runs it should look like this: [1,2,3,4, ...]

//This doesn't work
function addNumber() {
    numbers.push(numbers.length + 1); //The variable is not reassigned
}

//This does work!
function addNumber() {
    numbers.push(numbers.length + 1);
    numbers = numbers; //This is the reassignment
}

// OR
function addNumber() {
    numbers = [...numbers, numbers.length + 1]; //And this is also the reassignment
}

还有一些针对您的问题的示例代码:

messages = [] //TODO: Have a function that appends a message to the array and forces the {#each} "loop" to update

//This doesn't work
function addMessage(newMessage) {
    messages.push(newMessage); // It's just adding to the array but the array isn't "registered" as updated
}

//This does work!
function addMessage(newMessage) {
    messages.push(newMessage);
    messages = messages; //This is the reassignment and causes the update
}

// OR
function addMessage(newMessage) {
    messages = [...messages, newMessage]; //Another way to add to it and reassign it to also cause an update
}

所以我认为你必须改变将消息附加到messages数组的方式。

参考和示例:https ://svelte.dev/tutorial/updating-arrays-and-objects

更多推荐

我将,苗条,如何在

本文发布于:2023-04-21 02:58:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/hyzx/001581c423371b47803f1434c3cd9a21.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我将   苗条   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!