更新单个 DataTable 单元格而不重新呈现整个 table

Update individual DataTable cells without re-rendering entire table

我有一个数据表,我想用股票市场价格更新它(使用间隔回调)。 table 很大,所以我不想每次价格变化时都重新渲染整个 table。是否可以只更新包含已更改的特定股票价格的单元格?基本上,我希望价格单元格能够快速顺利地更新,而无需重新加载其他所有内容。这是否可以使用常规 Dash 组件,或者我是否需要使用 React 创建自己的 table 并在 React 端处理价格更新?欢迎任何想法。谢谢!

DataTable 组件提供分页正是为了不必在屏幕上呈现所有数据,默认情况下启用并设置为每页 250 行。

Pagination is used to improve performance: instead of rendering all of the rows at once (which can be expensive), we only display a subset of them. With pagination, we can either page through data that exists in the table (e.g. page through 10,000 rows in data 100 rows at a time) or we can update the data on-the-fly with callbacks when the user clicks on the "Previous" or "Next" buttons. These modes can be toggled with the page_action parameter.

恕我直言,最好的选择是利用它并让前端相应地完成工作。加号是,当获取股票市场价格时,屏幕上只能更新从零到 250(或 )行,因此在大多数情况下(具有合理的页面大小)它保证快速和平滑过渡。

参数为:

  • page_action(默认值:'native')
  • page_size(默认值:250)
  • page_current(默认值:0)
  • page_count(可选)

另一个想法(不排除使用分页)是将间隔回调集数据更新到 dcc.Store 组件,而不是直接更新 table。然后可以在客户端读取商店中的数据,这允许使用 javascript.

手动处理单元格更新

例如,将当前时间作为数据发送:

from datetime import datetime as dt

@app.callback(
    Output('store-id', 'data'),
    Input('interval-id', 'n_intervals')
)
def refresh_data(n_intervals):
    data = {'time': dt.now().strftime('%H:%M:%S')}
    return data

然后你也可以注册一个clientside callback来从客户端读取这些数据并在触发时进行更新:

app.clientside_callback(
    '''
    function(data) {
        // data is a JSON object. 
        console.log("callback receives", data);

        // Here you can either update the Output component the 
        // Dash way (<output> is the DataTable component id) :
        // return data;

        // Or if you need more freedom, you would use a dummy output 
        // (all Dash callbacks must have at least one output) and 
        // tell Dash to not update it, for example : 
        updateTable(data);
        return window.dash_clientside.no_update;
    }
    ''',
    Output('<output>', '<property>'),
    [Input('store-id', 'data')]
)

也取决于 storage_type :对于 localsession 你总是可以使用 localStoragesessionStorage 来获取数据作为 JSON 字符串, 例如

data = JSON.parse(localStorage.getItem('store-id'));

使用 storage_type='memory' 似乎无法在客户端回调之外获取数据(尽管我没有进一步搜索)。