Dash应用输入框值无法在刷新/页面切换后持久化,求排查
Dash输入框数据持久化失效的解决方法
你的代码里所有输入框都没加唯一的id属性,这是Dash组件实现数据持久化的必要条件——Dash需要通过id来关联存储的用户输入值和对应的组件,没有id的话,持久化机制根本无法工作。
只需要给每个dbc.Input添加唯一的id即可解决问题,修改后的代码示例如下:
from dash import Dash import dash_bootstrap_components as dbc dbc_css = ( "https://cdn.jsdelivr.net/gh/AnnMarieW/dash-bootstrap-templates@V1.0.2/dbc.min.css" ) app = Dash( __name__, suppress_callback_exceptions=True, external_stylesheets=[dbc.themes.BOOTSTRAP, dbc_css], ) # With placeholder ip1 = dbc.Input(id="input1", placeholder="Please input count of persons", persistence=True) ip2 = dbc.Input(id="input2", placeholder="Please input count of persons", persistence=True, persistence_type="session") ip3 = dbc.Input(id="input3", placeholder="Please input count of persons", persistence=True, persistence_type="session", persisted_props="value") # Without placeholder ip4 = dbc.Input(id="input4", persistence=True) ip5 = dbc.Input(id="input5", persistence=True, persistence_type="session") ip6 = dbc.Input(id="input6", persistence=True, persistence_type="session", persisted_props="value") app.layout = dbc.Container([ip1, ip2, ip3, ip4, ip5, ip6]) if __name__ == "__main__": app.run(host="0.0.0.0", port="8001", debug=True)
额外补充几个关键点:
persistence_type可选值为"memory"(仅当前页面有效,刷新就丢)、"session"(浏览器会话内有效,关闭浏览器清空)、"local"(本地长期存储,除非手动清除浏览器数据),按需选择即可。persisted_props默认就是"value",所以不需要显式指定,除非你需要持久化组件的其他属性。
内容的提问来源于stack exchange,提问作者winter
相关产品推荐
相关产品推荐

