闪亮 UI 模块问题:服务器模块未使用反应式表达式更新选择

Shiny UI Module Issue: server module not updating choices with reactive expression

我在搜索过滤模块工作时遇到了很多麻烦。

我要 运行 统计猫主人信息的大型数据库。 我希望我的搜索模块根据猫品种列表中的 selection 列出可能的所有者(用户可以 select 来自)。 我认为用 observe 包装 updateSelectInput 并使用响应式 cat owner 表达式会在模块中促进这一点,但它不起作用(我无法猜测为什么会发生这种情况或如何调试它)。它在这些其他帖子中起作用([1]:R shiny passing reactive to selectInput choices , [2]:using values from a reactive input to directly input into a custom function)

为什么我的 select 与猫主人的输入不更新?

library(shiny)
df=data.frame(
  cat=c("tabby","DSH","MSH","LSH","DSH","MSH","LSH","sphinx"),
  owner=c("Foo","Bar","Bash","Foo","Foo","Foo","Bar","Bash"),stringsAsFactors = F)
refinedSearch<-function(input, output, session){
  ownsCat<-reactive({df[df$cat%in%input$cat,"owner"]})
  observe({updateSelectInput(session, "ownerSelected",
                             label ="Owned By",choices = ownsCat())})
  return()
}
refinedSearchUI<-function(id){
  ns <- NS(id)
  fluidRow(
    column(4,selectInput(ns("cat"),"Cat",selectize = T, 
                         choices =c("tabby","DSH","MSH","LSH","sphinx") )),
    column(4,selectInput(ns("ownerSelected"),"Owned By","",selectize = T))
  )
}
ui <- fluidPage(
  h1("Find cats owners"),
  fluidRow(column(10,offset=1, refinedSearchUI("tmp"))),
  fluidRow(column(10,offset=1, actionButton("addFilter","Add a Filter",
                                            icon = icon("plus"))))
)
server <- function(input, output,session) {
  refinedSearch(input,output,session)
  observeEvent(input$add, {insertUI(selector = "#addFilter",where = "beforeBegin",
                                    ui = refinedSearch(input,output,session))})
}
shinyApp(ui = ui, server = server)

谢谢大家的宝贵时间。

关于如何调用模块似乎有点混乱。您需要在服务器中使用 callModule() 功能。此外,当插入 UI(使用 insertUI() 函数)时,您需要调用 refinedSearchUI() 函数,而不是 refinedSearch() 函数(同样,应该始终通过callModule(),所以它永远不应该像那样直接调用。

我建议重新阅读 the modules article

你也有错别字。 observeEvent() 函数中的事件应该是 input$addFilter,而不是 input$add(它不存在,因此永远不会触发观察者..)

如果您将服务器功能更改为此,您的应用将按预期运行:

server <- function(input, output,session) {
  callModule(refinedSearch, "tmp")

  observeEvent(input$addFilter, {
    id <- paste0("filter_", input$add)
    insertUI(selector = "#addFilter",where = "beforeBegin",
             ui = refinedSearchUI(id))
    callModule(refinedSearch, id)
  })
}