在 Shiny 服务器启动时触发用于 selectInput 的 Shiny R observeEvent

Anu*_*wal 3 r shiny

下面是一个示例 Shiny 应用程序:

用户界面

shinyUI(fluidPage(

  # Application title
  titlePanel("Test select input event"),
  sidebarLayout(
    sidebarPanel(
      selectInput('testSelect', 'Test',choices = c(1,2,3), multiple = FALSE)
    ),
    mainPanel(
    )
  )
))
Run Code Online (Sandbox Code Playgroud)

服务器.R

shinyServer(function(input, output) {

  observeEvent(input$testSelect,{ print("I am getting trigerred unnecessarily")})

})
Run Code Online (Sandbox Code Playgroud)

当我启动这个应用程序时,控制台日志立即显示:

http://127.0.0.1:5017
[1] “我不必要地被触发”

似乎observeEvent在应用程序开始时不必要地触发了选择输入。有人可以解释这种行为吗?

Gre*_*lia 7

有一个ignoreInit参数observeEvent可以处理此类不需要的触发器。以下代码将阻止在启动时显示该消息。

library(shiny)

shinyApp(
  selectInput('testSelect', 'Test', choices = c(1, 2, 3)),
  function(input, output, session){
    observeEvent(
      input$testSelect,                                     ## eventExpr
      {print("I am NOT getting trigerred unnecessarily")},  ## handlerExpr
      ignoreInit = TRUE
    )
  }
)
Run Code Online (Sandbox Code Playgroud)

参数 (in ?observeEvent)的文档提供了有关observeEvent启动时如何操作的很好的见解。

ignoreInit

如果TRUE,那么,当它observeEvent第一次被创建/初始化时,忽略handlerExpr(第二个参数),不管它是否应该运行。默认值为FALSE. 查看详细信息。

详细信息部分进一步阐明了这一点。

从详细信息:默认情况下,observeEvent将在创建时立即运行(除非当时eventExpr评估为NULL并且ignoreNULLTRUE

observeEvent创建时,input$testSelect将具有值1,因此handlerExpr(即print命令)被触发,除非ignoreInit设置为它的非默认值TRUE