我正在显示一个包含用户聊天的JSON对象的列表。如果用户在搜索栏中键入某些内容,则将原始chats列表中的匹配JSON对象推入新的filtered_chats数组中。我没有包含这个代码逻辑,因为这是可行的,并且正在填充filtered_chats。(注意:filtered_chats从脚本标记中的空数组开始。也许这是有用的)
我面临的问题是,SvelteKit不会将新数组提供给filtered_chats,只显示来自filtered_chats的元素,而不会显示来自chats的所有聊天。它只检查原始数组,并保留已呈现的内容。
剧本:
<script lang="ts">
import ChatSidebarElement from "$components/ChatSidebarElement.svelte";
export let chats : JSON;
var filtered_chats = [];
var searchval = "";
function search() {
// this pushes chat objects into "filtered_chats" if they match the search pattern
}HTML:
<div class="mb-4">
<input type="search" class="form-control text-dark" bind:value={searchval} on:input={search} placeholder="Search chats">
</div>
<h3 class="text-light">Open Chats</h3>
{#if chats.length > 0}
<div class="chats">
{#if filtered_chats.length > 0}
<h1 class="text-light">{searchval}</h1>
{#each filtered_chats as chat}
<ChatSidebarElement chat={chat}></ChatSidebarElement>
{/each}
{:else}
{#each chats as chat}
<ChatSidebarElement chat={chat}></ChatSidebarElement>
{/each}
{/if}
</div>
{:else}
<li>
<div class="info">
<div>You don't have any open chats!</div>
</div>
</li>
{/if}发布于 2022-10-10 17:48:56
Svelte只在重新分配变量时更新UI。考虑到这一点,如果您改变了一个数组,而不是用一个新的状态重新分配它,它将不会更新UI。例如:
<script>
let items = ['1', '2', '3']
// Wrong! UI won't be updated
items.push('4')
// Right! UI gets updated
items = [...items, '4']
// Or you can also do this
items = items.concat('4')
</script>https://stackoverflow.com/questions/73611992
复制相似问题