R语言 Shiny应用程序中的等效观察员,但行为不同

mlmc2os5  于 2023-04-18  发布在  其他
关注(0)|答案(1)|浏览(114)

这两款Shiny应用的区别在于,第一款包括

observeEvent(
    input$alert,
    {
      flag(TRUE)
    }
  )

而在第二个代码中,此代码被替换为以下代码:

observeEvent(
    list(input$alert, input$X),
    {
      flag(TRUE)
    }, ignoreInit = TRUE
  )

其中input$X始终为NULL
但是这两个应用程序有不同的行为(点击几次按钮)。为什么?我不明白第二个的行为。

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  mainPanel(
    actionButton(
      inputId = "button",
      label = "ALERT"
    )
  )
)

server1 <- function(input, output, session) {
  
  flag <- reactiveVal(NULL)
  
  observeEvent(
    input$button,
    {
      confirmSweetAlert(
        inputId = "alert",
        title = "ALERT",
        type = "error"
      )
    }
  )
  
  observeEvent(
    input$alert,
    {
      flag(TRUE)
    }
  )
  
  observeEvent(
    flag(),
    {
      flag(NULL)
      sendSweetAlert(
        title = "ALERT 2",
        type = "error"
      )
    }
  )
  
}

server2 <- function(input, output, session) {
  
  flag <- reactiveVal(NULL)

  observeEvent(
    input$button,
    {
      confirmSweetAlert(
        inputId = "alert",
        title = "ALERT",
        type = "error"
      )
    }
  )

  observeEvent(
    list(input$alert, input$X),
    {
      flag(TRUE)
    }, ignoreInit = TRUE
  )

  observeEvent(
    flag(),
    {
      flag(NULL)
      sendSweetAlert(
        title = "ALERT 2",
        type = "error"
      )
    }
  )
  
}

shinyApp(ui = ui, server = server1)
shinyApp(ui = ui, server = server2)
h6my8fg2

h6my8fg21#

不同的行为是由于list(NULL, NULL)不是NULL(导致flag被设置为TRUE):

> is.null(list(NULL, NULL))
[1] FALSE

observeEvent默认使用ignoreNULL = TRUE
server1中设置ignoreNULL = FALSE会导致与server2相同的行为:

server1 <- function(input, output, session) {
  
  flag <- reactiveVal(NULL)
  
  observeEvent(
    input$button,
    {
      confirmSweetAlert(
        inputId = "alert",
        title = "ALERT",
        type = "error"
      )
    }
  )
  
  observeEvent(
    input$alert,
    {
      flag(TRUE)
    }, ignoreNULL = FALSE
  )
  
  observeEvent(
    flag(),
    {
      flag(NULL)
      sendSweetAlert(
        title = "ALERT 2",
        type = "error"
      )
    }
  )
  
}

作为替代,在server2中使用c(input$alert, input$X)而不是list(input$alert, input$X)

> is.null(c(NULL, NULL))
[1] TRUE
server2 <- function(input, output, session) {
  
  flag <- reactiveVal(NULL)
  
  observeEvent(input$button,
    {
      confirmSweetAlert(
        inputId = "alert",
        title = "ALERT",
        type = "error"
      )
    }
  )
  
  observeEvent({c(input$alert, input$X)},
    {
      flag(TRUE)
    }, ignoreInit = TRUE
  )
  
  observeEvent(
    flag(),
    {
      flag(NULL)
      sendSweetAlert(
        title = "ALERT 2",
        type = "error"
      )
    }
  )
  
}

相关问题