r语言 - 相同的观察者在闪亮的应用程序,但不同的行为



两个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)

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

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

andobserveEvent默认使用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"
)
}
)

}

相关内容

  • 没有找到相关文章

最新更新