You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R Shiny技术问题:点击actionButton后在datatable加载前显示spinner

解决Shiny中点击按钮后DataTable加载前显示Spinner的问题

问题根源

你的代码存在两处核心问题:

  1. 直接在observeEvent内赋值output$table_properties,这种方式无法触发withSpinner的加载状态——Shiny的响应式系统需要通过响应式对象的变化来识别加载过程。
  2. 测试代码中没有模拟数据加载的延迟(实际场景里数据库查询会有耗时,但你当前直接赋值数据,导致Spinner来不及显示)。

修正后的完整代码

library(DT)
library(shiny)
library(shinycssloaders)

ui <- fluidPage(
  navbarPage("Query Tool",
             navbarMenu("Structures",
                        tabPanel("Structure Properties", fluid = TRUE,
                                 sidebarLayout(
                                   sidebarPanel(
                                     textInput("structure_id_properties", strong("Structure:"), value = ''),
                                     actionButton("run_properties", "Run Analysis", icon = icon("play"))),
                                   mainPanel(
                                     tabsetPanel(type = "tabs",
                                                 # 保留withSpinner包裹DTOutput的写法
                                                 tabPanel("Data Table", br(), withSpinner(DTOutput("table_properties")))
                                     ))
                                 ))))) 

server <- function(input, output) {
  # 用eventReactive响应按钮点击,生成响应式数据对象
  reactive_data <- eventReactive(input$run_properties, {
    # 模拟数据加载延迟(实际场景替换为你的sql_data查询逻辑)
    Sys.sleep(2)
    # 替换为你的实际数据处理逻辑,比如data_output(sql_data)
    data.frame(ID = 1:10, Name = paste0("Item_", 1:10), Value = rnorm(10))
  })
  
  # 基于响应式数据渲染DT,此时withSpinner会在数据加载时自动显示
  output$table_properties <- renderDT({
    reactive_data()
  })
  
  # 响应式生成SQL语句(如果需要)
  reactive_sql <- eventReactive(input$run_properties, {
    # 替换为你的实际SQL生成逻辑
    "SELECT * FROM structure_properties WHERE id = 'test'"
  })
  
  output$query_properties <- renderText({
    reactive_sql()
  })
}

shinyApp(ui, server)

核心修改说明

  • 用eventReactive创建响应式数据/对象,替代直接在observeEvent中赋值output,让Shiny能正确识别数据加载状态,触发Spinner。
  • 添加Sys.sleep(2)模拟实际查询的耗时(实际使用时可删除,保留你的数据库查询代码),确保Spinner有足够时间展示。
  • 分离数据生成与输出渲染逻辑,符合Shiny响应式系统的工作机制。

内容的提问来源于stack exchange,提问作者AVE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 23:10:26