Python Dash中Location重定向后出现children对象类型错误
Dash中dbc.Tooltip跳转页面后报错的原因与解决方法
问题场景
我有一个最简可运行的Dash应用,包含可跳转至其他页面的按钮,代码如下:
import dash from dash import dcc from dash import html import dash_bootstrap_components as dbc from dash.dependencies import Input, Output app = dash.Dash(__name__, suppress_callback_exceptions=True) app.layout = html.Div([ dcc.Location(id='url', refresh=False), html.Div(id='page-content'), ]) def get_overview_page(): page = html.Div([ dcc.Link( html.Button('Neu', id='new_button', style={'margin-left': '10px', 'width': '100px', 'height': '27px', 'fontSize': '16px'}), href='/new-entry' ), dbc.Tooltip( "A.", target="new_button", placement="top" ) ], style={'width': '30%', 'margin-top': '10px', 'display': 'inline-block', 'text-align': 'left'}) return page # Update the index @app.callback(Output('page-content', 'children'), [Input('url', 'pathname')]) def display_page(pathname): if pathname == '/new-entry': return html.Div() else: return get_overview_page() if __name__ == '__main__': app.run_server(debug=True, port=8086, host='127.0.0.1')
点击按钮跳转后移动鼠标,出现错误提示:
An object was provided as
childreninstead of a component, string, or number (or list of those). Check the children property that looks something like: { "1": {
"props": {
"is_open": false
} } }
移除dbc.Tooltip后错误消失,但需要保留Tooltip,请问问题原因是什么?该如何解决?
问题原因
当跳转到/new-entry页面时,原页面的new_button按钮被从DOM中移除,但dbc.Tooltip是带内部状态的组件(管理is_open状态),Dash后台残留了该Tooltip的状态信息,当鼠标移动触发组件更新时,Dash尝试渲染一个已不存在的组件,从而抛出格式错误。
解决方法
方式1:给Tooltip添加唯一ID
给dbc.Tooltip指定唯一的id属性,让Dash能够正确跟踪组件状态,避免残留状态引发错误:
def get_overview_page(): page = html.Div([ dcc.Link( html.Button('Neu', id='new_button', style={'margin-left': '10px', 'width': '100px', 'height': '27px', 'fontSize': '16px'}), href='/new-entry' ), dbc.Tooltip( "A.", id="tooltip-new-button", # 添加唯一ID target="new_button", placement="top" ) ], style={'width': '30%', 'margin-top': '10px', 'display': 'inline-block', 'text-align': 'left'}) return page
方式2:将按钮与Tooltip封装为整体
把按钮和Tooltip放在同一个容器内,确保页面切换时两者作为一个整体被替换,避免Tooltip单独残留:
def get_overview_page(): page = html.Div([ html.Div([ dcc.Link( html.Button('Neu', id='new_button', style={'margin-left': '10px', 'width': '100px', 'height': '27px', 'fontSize': '16px'}), href='/new-entry' ), dbc.Tooltip( "A.", target="new_button", placement="top" ) ]) ], style={'width': '30%', 'margin-top': '10px', 'display': 'inline-block', 'text-align': 'left'}) return page
内容的提问来源于stack exchange,提问作者aushdk
相关产品推荐
相关产品推荐

