RShiny 中的响应式(Reactive)输入 react 太快(不使用按钮)

标签 r shiny shiny-server shinyapps shiny-reactivity

如何才能让 Shiny 等待用户输入邮政编码(不使用按钮)。我面临的问题是,如果用户输入邮政编码的速度不够快,它会很快跳转到错误。 编辑:

  • 我在这个应用程序中有其他用户输入,但我在这个问题中简化了它。我希望所有其他输入立即使用react,因为它们是单选按钮。我认为按“返回”仍然会执行与按钮相同的操作,这不是我想要的。我正在考虑仅将“Sys.sleep()”用于邮政编码输入,而不用于其他输入。这可能吗?
library(shiny)

shinyApp(ui <- fluidPage(sidebarPanel(
  "",
  textInput("zipcode", label = "Enter your zipcode.", value = 98125)
  
)) ,


server <- function(input, output, session) {
  observeEvent(input$zipcode, {
    #limits zipcode input to 5 numbers only
    if (nchar(input$zipcode) != 5)
    {
      updateTextInput(session, 'zipcode', value = 98125)
      showModal(
        modalDialog(
          title = "Error!",
          "Only 5-character entries are permitted.",
          easyClose = TRUE
        )
      )
    }
    if (is.na(as.numeric(input$zipcode)))
    {
      showModal(
        modalDialog(
          title = "Error!",
          "Only numeric values are allowed. Please try again.",
          easyClose = TRUE
        )
      )
    }
  })
})

最佳答案

您可以使用debounce :

This lets you ignore a very "chatty" reactive expression until it becomes idle, which is useful when the intermediate values don't matter as much as the final value

您不需要 Sys.sleep,它会在触发 react 之前等待 millis 毫秒:

library(shiny)

shinyApp(
  ui <- fluidPage( 
    sidebarPanel("", textInput("zipcode", label="Enter your zipcode.", value = 98125)
                 
    )  ) , 
  
  
  server <- function(input, output, session) {
    zipcode <- reactive(input$zipcode)
    zipcode_d <- debounce(zipcode, millis = 2000)
    observeEvent(zipcode_d(),{     #limits zipcode input to 5 numbers only
      if(nchar(zipcode_d())!=5)
      {
        updateTextInput(session,'zipcode',value=98125)
        showModal(modalDialog(
          title = "Error!",
          "Only 5-character entries are permitted.",
          easyClose = TRUE
        ))
      }
      if(is.na(as.numeric(zipcode_d())))
      {
        showModal(modalDialog(
          title = "Error!",
          "Only numeric values are allowed. Please try again.",
          easyClose = TRUE
        ))
      }
    }
    )
  })

关于RShiny 中的响应式(Reactive)输入 react 太快(不使用按钮),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63982940/

相关文章:

r - 使用数据框列的级别添加一个新列,每个级别都有唯一的递增编号

r - R 包 mlr 的(二进制)因子变量应该有哪些类?

r - 具有多种美学效果的绘图中缺少手动图例(scale_colour_manual)

r - 如何使用 Shiny Pro 访问 Shiny 中的 session$user

mysql - rmysql返回数据类型

r - 传单绘图工具栏 : allow only editing and deleting but not adding new markers in R Shiny

r - 从 server.R 调用 "bind"-ed 输入

R Shiny 加载工作区

shiny - Chrome 浏览器不会显示页面,除非已经在 Shiny 中打开

r - 没有事件的 react 上下文不允许操作