R Shiny - 重置 shinyTree 节点选择

R Shiny - Resetting shinyTree node selections

下面的应用程序包含一个 shinyTree、一个重置按钮 (Reset nodes) 和一个打印输出 'Selected nodes'。打印输出打印 get_selected 函数的输出,其中 return 是所选节点的列表。

这是树启动时的屏幕截图:

未选择任何节点,因此 get_selected return 为空 list()

当我做出选择时,例如节点 aget_selected 正确 return 选择:

当我单击 Reset nodes 时,树中的节点选择被清除 UI 但 get_selected 与之前的选择没有变化:

单击重置按钮时,观察者通过 updateTree 更新树如下:

observeEvent(input$reset, {

    updateTree(session,"tree", data = tree)
  })

当我点击重置时,我希望 get_selected 到 return list()。我使用 updateTree 不正确吗?

下面是重现上述内容的代码:

library(shiny)
library(shinyTree)

tree = structure(list(a=list(a1=1,a2=2) , b="b"), stopened = T) 

tree = lapply(tree, function(x) structure(x, stopened = T))

ui <- fluidPage(
  tags$head(tags$script('
                        $("#reset").onlick(function() {
                        $("#tree").jstree("deselect_all");
                        }
                        ')),
  fluidPage(
    sidebarLayout(
      sidebarPanel(
        actionButton('reset', 'Reset nodes')
      ),
      mainPanel(
        shinyTree("tree", ),
        hr(),
        "Selected nodes:",
        verbatimTextOutput("idSelected")#,
      )
    )
  )
)

# server

server <- function(input, output, session) {

  output$tree = renderTree({

    tree

  })


  output$idSelected <- renderPrint({
    str(get_selected(input$tree, format = "classid"))
  })


  # An observer is used to trigger a tree update when reset is clicked.
  observeEvent(input$reset, {

    updateTree(session,"tree", data = tree)

    print(get_selected(input$tree, format = "classid"))
  })
}

shinyApp(ui, server)

我尝试了以下 JQuery 无济于事:

$("#reset").onlick(function() {
                        $("#tree").jstree("deselect_all");
                        }

您可以在按下重置按钮时更新 reactiveVal,而不是直接引用 get_selected 提供的数据:

library(shiny)
library(shinyTree)

tree <- lapply(structure(list(a=list(a1=1,a2=2) , b="b"), stopened = TRUE) , function(x) structure(x, stopened = TRUE))

ui <- fluidPage(
  fluidPage(
    sidebarLayout(
      sidebarPanel(
        actionButton('reset', 'Reset nodes')
      ),
      mainPanel(
        shinyTree("tree", ),
        hr(),
        "Selected nodes:",
        verbatimTextOutput("idSelected")#,
      )
    )
  )
)

server <- function(input, output, session) {

  treeSelection <- reactiveVal(list())

  output$tree = renderTree({
    tree
  })

  observeEvent(input$reset, {
    updateTree(session, "tree", data = tree)
    treeSelection(list())
  })

  observeEvent(input$tree, {
    treeSelection(get_selected(input$tree, format = "classid"))
  })

  output$idSelected <- renderPrint({
    treeSelection()
  })

}

shinyApp(ui, server)