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
更多推荐
我将,苗条,如何在
发布评论