我不知道如何在使用 dcc.Store 时清除本地存储

I cannot figure out how to clear the local store when using dcc.Store

我在搞dcc.Store (https://dash.plot.ly/dash-core-components/store)

有一个 clear_data 属性,但我不知道如何让它发挥作用。我想添加一个 html 按钮来清除本地商店。

我所做的只是递增一个变量,存储它并读回它...... Dash 给出的示例没有给出任何指示如何清除值

import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Output, Input, State
from dash.exceptions import PreventUpdate


app = dash.Dash(__name__)
app.config['suppress_callback_exceptions']=True

app.layout = html.Div([

    dcc.Store(id='buttonstore3', storage_type='local'),

    html.Div([
        html.Button('Local', id='my-button3')
    ]),

    html.Div([
        html.Button('Clear Local', id='my-button4')
    ]),


    html.Div([
        html.Table([
            html.Thead([
                html.Tr([
                    html.Th('Local clicks')
                ])
            ]),
            html.Tbody([
                html.Tr([
                    html.Td(0, id='local-clicks'),
                ])
            ])
        ])
    ])


])


####### Add to Local Store
@app.callback(Output('buttonstore3', 'data'),
                [Input('my-button3', 'n_clicks')],
                [State('buttonstore3', 'data')])
def on_click(n_clicks, data):
    if n_clicks  is None:
        raise PreventUpdate

    data = data or 0
    data = data + 1
    return data


@app.callback(Output('local-clicks', 'children'),
                [Input('buttonstore3', 'modified_timestamp')],
                [State('buttonstore3', 'data')])
def on_data(ts, data):
    if ts is None:
        raise PreventUpdate

    data = data or 0
    return data


if __name__ == '__main__':
    app.run_server(debug=True, threaded=True)

文档中说 here:

clear_data - Set to True to remove the data contained in data_key.

因此您可以将以下回调添加到您的应用中:

@app.callback(Output('buttonstore3', 'clear_data'),
            [Input('my-button4', 'n_clicks')])
def clear_click(n_click_clear):
    if n_click_clear is not None and n_click_clear > 0:
        return True
    return False

您还可以更新 on_click 回调以接收来自两个按钮的输入,并根据点击的按钮输出到 data 属性,如下所示:

####### Add to Local Store
@app.callback(Output('buttonstore3', 'data'),
                [Input('my-button3', 'n_clicks'),
                Input('my-button4', 'n_clicks')],
                [State('buttonstore3', 'data')])
def on_click(n_clicks_add, n_clicks_clear, data):
    if n_clicks_add is None:
        n_clicks_add = 0
    if n_clicks_clear is None:
        n_clicks_clear = 0
    if data is None:
        data = 0

    trigger = dash.callback_context.triggered[0]

    if trigger['prop_id'] == 'my-button3.n_clicks':
        data += 1
    elif trigger['prop_id'] == 'my-button4.n_clicks':
        data = 0
    else:
        raise ValueError('Unrecognized trigger: {}'.format(trigger['prop_id']))

    return data