Shiny:Shiny Dashboard中的renderMenu和observeEvent冲突(sidebarMenu)

时间:2017-09-13 00:46:19

标签: r shiny shinydashboard

我的目标是构建菜单,其中内容是动态生成的,用户只能看到从顶部到所选内容的menuItems / menuSubItems(" next"按钮将用于到达下一个尚未显示的menuItems / menuSubItems;如果选择任何可用的menuItems / menuSubItems菜单,则应重新生成菜单,以便选择最后一个可用的menuItems / menuSubItems)。因此,我必须使用选定的 startExpanded 参数,但这不是此问题的一部分。

我遇到的问题是renderMenuobserveEvent的相互连接(检查选定的menuItem / menuSubItem)。这是代码:

library(shiny)
library(shinydashboard)

menu_generator <- function(selected = NULL, expanded = NULL){

  print("menu_generator")

  output <- sidebarMenu(

    menuItem("Charts1", icon = icon("bar-chart-o"),
             menuSubItem("AAdashboard", tabName = "AAdashboard"),
             menuSubItem("BBdashboard", tabName = "BBdashboard")
    ),
    menuItem("Charts2", icon = icon("bar-chart-o"),
             menuSubItem("DDdashboard", tabName = "DDdashboard"),
             menuSubItem("EWidgets", tabName = "EWidgets")
    )

  )

  return(output)
}

ui <- dashboardPage(
  dashboardHeader(title = "Test"),
  dashboardSidebar(sidebarMenu(
    sidebarMenuOutput("menu_output")
  )),
  dashboardBody(
    tabItems(
      tabItem(tabName = "AAdashboard",
              h2("ADashboard tab content")
      ),

      tabItem(tabName = "BBdashboard",
              h2("BWidgets tab content")
      ),

      tabItem(tabName = "DDdashboard",
              h2("DWidgets tab content")
      ),

      tabItem(tabName = "EWidgets",
              h2("EWidgets tab content")
      )
    ))
)


server <- function(input, output) {

  output$menu_output <- renderMenu({
    print("output$menu_output")
    sidebarMenu(menu_generator(),
                id = "my_menu")

  })

  observeEvent(input$my_menu, {

    print("observer")

    print(input$my_menu)
    print(input$sidebarItemExpanded)

    output$menu_output <- renderMenu({
      sidebarMenu(menu_generator(),
                  id = "my_menu")
    })
  })


}

shinyApp(ui, server)

场景:展开Charts2,然后点击&#34; DDdashboard&#34;。

在控制台中:

[1] "observer"
[1] "DDdashboard"
[1] "Charts2"
[1] "menu_generator"
[1] "observer"
[1] "AAdashboard"
NULL
[1] "menu_generator"

&#34;观察者&#34;被调用两次(因此&#34; menu_generator&#34;也),因此这会产生意外行为。我的理解是,原因是renderMenu的性质。问题是 - 如何防止Shiny呼叫&#34;观察者&#34;在这种情况下两次?另请注意,在第二个电话input$my_menu =&#34; AAdashboard&#34;。

1 个答案:

答案 0 :(得分:-1)

observeEvent(input$sidebarItemExpanded == 'DDdashboard',{

print("DDdashboard_selected")

  })