2

我正在尝试在 Svelte 商店中维护实时股票报价,以便实时更新屏幕上的出价和要价。我不确定如何构建存储以保持数据的反应性和效率。数据来自 websocket,如下所示:

{'symbol':'AAPL', 'bid':305.52, 'ask':305.55}

我最初的尝试如下所示:

import { readable, writable } from 'svelte/store';

export let quotes = {}

function addQuotes(sym) {
  const quote = writable({
    bid: 0,
    ask: 0
  });
  quotes[sym] = quote;
}

我想要做的是在整个 SPA 中提供一个单一的报价地图,但每次更改时,每个单独的报价仅更新其自己的符号,而不是整个页面。

这显然是错误的,但我不确定该怎么做。(这是我第一次使用 Svelte。)

4

1 回答 1

0

You're on the right track.

Store the stock prices as a hash in a writable() store.

// in stores.js
export const stocks = writable({})

Then when you want to update the price or add a new stock, you call stocks.update().

// in stores.js
export function update(symbol, data) {
  // using `...` to destructure a copy, we don't want to overwrite previous value
  stocks.update(({...records}) => { 
    // now update the copy
    records[symbol] = data

    // return the new value for the store, this will trigger updates in templates that subscribe 
    return records
  })
}

In your .svelte component, import the store.js

<script>
  import {stocks, update} from './store.js'
  import {onMount} from 'svelte'

  update('AAPL', {ask: 10, bid: 20})
  update('MSFT', {ask: 10, bid: 20})

  onMount(() => {
    setTimeout(() => update('AAPL', {ask: 10.20, bid: 10.25}), 2000)
    setTimeout(() => update('AAPL', {ask: 10.30, bid: 10.35}), 4000)
  })
</script>

<!-- use dollar sign in front of store name to make svelte auto-subscribe -->

<pre>
  {JSON.stringify($stocks, null, 2)}
</pre>
于 2020-01-10T09:44:57.887 回答