Dash多页面应用中页面间数据共享及程序化导航问题
解决Dash多页面应用程序化跳转问题
问题根源
你当前的回调逻辑错误地将dcc.Location组件作为返回值传递给hidden_div的children属性,而Dash的路由跳转需通过直接修改dcc.Location的pathname属性实现;同时代码还存在表格ID缺失、参数名不匹配的问题。
修复步骤及代码示例
1. 修正页面布局
在布局中添加dcc.Location组件管理路由,同时给表格补充id='tbl'(与回调输入对应):
layout = dbc.Container([ dcc.Location(id='url', refresh=False), # 添加路由管理组件 html.Div(children='Experiement Results'), dbc.Button("Image Browser", id='image-browser', color="dark", className="me-1"), dbc.Button("Experiment Result", id='exp-result', color="dark", className="me-1"), html.Div([ dash_table.DataTable( id='tbl', # 补充表格ID,与回调输入匹配 data=df, columns=[{'id':c, 'name':get_field_display_name(c), 'type':get_field_type(c)} for c in df[0].keys()], page_size=100, row_selectable='single', cell_selectable=True, filter_action='native', ) ]) ])
2. 修正回调逻辑
将输出目标改为dcc.Location的pathname属性,直接返回跳转路径字符串;同时修正参数名、添加选中行空值判断:
from dash import callback_context @callback( Output('url', 'pathname'), # 输出绑定到路由的pathname Input('image-browser', 'n_clicks'), Input('exp-result', 'n_clicks'), Input('tbl', 'selected_rows'), prevent_initial_call=True ) def button_pressed(image_browser, exp_result, selected_rows): changed_id = [p['prop_id'] for p in callback_context.triggered][0] # 先判断是否有选中行,避免索引报错 if not selected_rows: return None selected_id = selected_rows[0]['id'] # 假设行数据中'id'是你要传递的字段,根据实际结构修改 if 'image-browser' in changed_id: return f'/imagebrowser/{selected_id}' elif 'exp-result' in changed_id: return f'/expresult/{selected_id}' else: return None
3. 关键说明
- 路由跳转方式:Dash的程序化跳转通过修改
dcc.Location的pathname属性实现,无需返回组件实例 - 选中行处理:
selected_rows返回选中行的完整数据列表,需提取你需要的ID字段(示例假设字段名为id,请根据实际数据调整) - 空值判断:添加选中行的空值检查,防止用户未选中行就点击按钮导致报错
内容的提问来源于stack exchange,提问作者Krixen
相关产品推荐
相关产品推荐

