【发布时间】:2021-06-16 07:42:55
【问题描述】:
在以下示例中,我在“Tab1”中使用actionLink() 将显示切换到“Tab2”,然后将textInput() 中的文本更新为“iris”,最后单击按钮以显示实际数据。
由于未知原因,此开关在Sys.sleep() 之后执行。这会导致不希望的行为,因为shinyjs::click() 例如尝试触发一个尚不存在的按钮,因此不显示“虹膜”表。我本来希望首先切换选项卡,然后获取Sys.sleep()。
有人可以向我解释一下为什么 Shiny 会有这样的行为以及如何执行预期的行为吗?
library(shiny)
library(shinydashboard)
library(shinydashboardPlus) # shinydashboardPlus_0.7.5 // devtools::install_version("shinydashboardPlus", version = "0.7.5", repos = "http://cran.us.r-project.org")
library(shinyjs)
available_data_sets <- c("mtcars", "iris")
ui_welcome <- fluidPage(actionLink(inputId = "switch_tab", label = "Switch tab, update text with 'iris' & click button", icon = icon("hand-point-right")))
ui_search <- fluidPage(
textInput(inputId = "dataset_name", label = "Select data set", value = ""),
actionButton(inputId = "display_tab", label = "Display selected set"),
br(),
tableOutput('table'))
ui <- dashboardPagePlus(
collapse_sidebar = TRUE,
title = "Minimal",
header = dashboardHeaderPlus(
title = "Test",
enable_rightsidebar = FALSE,
rightSidebarIcon = "gears",
fixed = FALSE),
sidebar = dashboardSidebar(
sidebarMenu(
id = "left_sidebar",
menuItem("Tab1", tabName = "tab1", icon = icon("home")),
menuItem("Tab2", tabName = "tab2", icon = icon("search")))
),
body = dashboardBody(
useShinyjs(),
tabItems(tabItem(tabName = "tab1", ui_welcome),
tabItem(tabName = "tab2", ui_search)))
)
server <- function(input, output, session) {
# RENDER DATA
observeEvent(input$display_tab, {
print("Within observeEvent 'display_tab'")
selected <- input$dataset_name
print(paste0("Value of 'input$dataset_name' received: ", selected))
if(!isTruthy(selected)) return(NULL)
if(!selected %in% available_data_sets) return(NULL)
output$table <- renderTable(if(selected == "iris") iris else mtcars)
})
# SWITCH TAB & TRIGGER BTN
observeEvent(input$switch_tab, {
print("Within observeEvent 'switch_tab'")
print("updateTabItems"); updateTabItems(session, inputId = "left_sidebar", selected = "tab2")
print("updateTextInput 1"); updateTextInput(inputId = "dataset_name", value = "")
print("updateTextInput 2"); updateTextInput(inputId = "dataset_name", value = "iris")
print("Sys.sleep"); Sys.sleep(3)
print("shinyjs::click"); shinyjs::click(id = "display_tab")
})
}
shinyApp(ui, server)
【问题讨论】:
标签: r shiny shiny-reactivity