Shiny应用reactive picker input首次访问未按默认时段更新选项求解
解决方案
问题出在observeEvent的ignoreInit参数配置上:你设置了ignoreInit = TRUE,会让Shiny在应用初始化阶段跳过该观察者的执行,因此首次加载时不会根据默认选中的period1更新国家选择器的禁用状态,导致全部国家都可选。
只需将ignoreInit = TRUE修改为ignoreInit = FALSE,或者直接删除该参数(observeEvent默认该参数值为FALSE),即可让初始化阶段自动执行更新逻辑,首次加载就仅显示对应时段的可选国家。
修正后的完整代码如下:
library(shiny) library(shinyWidgets) choice_name <- c('UK','USA','BE','BE') choice_id <- c(1, 2, 3,3) period <- c('period1', 'period1', 'period3', 'period3') data <- data.frame(choice_name, choice_id, period) choices_picker <- unique(data$choice_id) names(choices_picker) <- unique(data$choice_name) ui <- bootstrapPage( absolutePanel(left = 10, bottom = 10, draggable = TRUE, selectInput(inputId = "input_period", label = "Period", choices = c("Period 1: X to Z" = "period1", "Period 2: X to Y" = "period2", "Period 3: X to X" = "period3"), selected = "period1"), pickerInput(inputId = "picker_cty", label = "Select Country", choices = choices_picker, multiple = TRUE), )) server <- function(input, output, session) { # Reactive pickerInput --------------------------------- observeEvent(input$input_period, { data1 <- data[data$period == input$input_period,] datau <- unique(data$choice_id) data1u <- unique(data1$choice_id) disabled_choices <- ifelse(datau %in% data1u, 0,1) # Generate reactive picker input updatePickerInput(session = session, inputId = "picker_cty", choices = choices_picker, choicesOpt = list( disabled = disabled_choices, style = ifelse(disabled_choices, yes = "color: rgba(119, 119, 119, 0.5);", no = "") )) }) # 移除了ignoreInit = TRUE参数 } shinyApp(ui, server)
注:当前示例数据集没有period2对应的国家记录,因此选中period2时所有国家都会被禁用,属于预期行为。
内容的提问来源于stack exchange,提问作者AnEostig
相关产品推荐
相关产品推荐

