我是 Svelte 的新手,我犯了一个菜鸟错误。我有一个到服务器的 websocket 连接,我正在记录数百条消息并将它们添加到商店,但页面根本没有更新。
App.svelte
<script>
import Socket from "./Socket.svelte"
import msgs from './stores'
</script>
<main>
<Socket items="{$msgs}"/>
</main>
套接字.svelte
<script>
export let items
</script>
{items.length}
{#if items}
{#each items as msg, i}
<p>{i} {msg}</p>
{/each}
{:else}
<p class="loading">waiting...</p>
{/if}
socket.js
import { readable, writable } from 'svelte/store';
let msgs = []
const msgStore = readable(msgs)
export default msgStore
const socket = new WebSocket("ws://localhost:8080/socket");
socket.binaryType = "arraybuffer";
socket.onopen = function (event) {
msgs = [...msgs, "Connected"];
};
socket.onmessage = function (event) {
msgs = [...msgs, event];
console.log(msgs.length)
const msg = JSON.parse(event.data)
const msgType = msg.messageType
console.log(msgType)
};
在浏览器中,我得到了0
items 数组的初始长度,但它永远不会更新,即使消息正在流动。