首页 > 解决方案 > 更新闪亮中相同单选按钮的选择参数

问题描述

我想从 R/shiny 中的 radioButtons-widget 更新选择参数。当用户选择一个选项时,choices 参数应该根据用户的第一个选项进行更新。我用样本函数用 4 个随机字母模拟了这个。看来更新并没有停止,而且更新了好几次。如何防止多次更新的行为?

这是重现我的方法的代码:

library("shiny")

ui <- fluidPage(
    radioButtons("answerchoice", label = "item", choices = sample(letters, 4), selected = NULL,
                 )
    
)

server <- function(input, output, session) {
    observeEvent(input$answerchoice,{
        updateRadioButtons(
            session = session,
            inputId = "answerchoice",
            choices = sample(letters, 4)
        )
    })
}

shinyApp(ui = ui, server = server)

标签: rshiny

解决方案


似乎默认设置selected = NULL可能是问题所在。radioButton最初选择一个值。这可能会导致多次更新。通过设置selected为空。该应用程序不会不受控制地更新。

library("shiny")

ui <- fluidPage(
  radioButtons("answerchoice",
               label = "item", 
               choices = sample(letters, 4),
               selected =  character(0)
  )
  
)

server <- function(input, output, session) {
  observeEvent(input$answerchoice,{
    updateRadioButtons(
      session = session,
      inputId = "answerchoice",
      choices = sample(letters, 4),
      selected =  character(0)
    )
  })
}

shinyApp(ui = ui, server = server)

推荐阅读