r - Shiny :在reactiveValues()上观察()

标签 r shiny reactive

我围绕 reactiveValues() 变量转储创建了一个 Shiny 的应用程序。使用 observeEvent() 观察一个简单的操作按钮,我使用自定义函数填充这些值。此外,我正在尝试观察其中一个 (Query$A),以便更新另一个输入元素。

shinyServer(function(input, output, session) {

    Query <- reactiveValues(A=NULL, B=NULL)

    observeEvent(input$SomeActionButton,{
        Query$A <- SomeCustomFunction(url)
        Query$B <- SomeOtherFunction(sqlScheme)
        updateSelectizeInput(session, "QueryScheme", choices =  Query$B)
    })

    observe(Query$A, {
        QueryNames <- sort(names(Query$B))
        updateSelectizeInput(session, "SortedSchemes", choices = QueryNames)
    })

})

这可能不会令一些更高级的 Shiny 开发人员感到惊讶,

Error in .getReactiveEnvironment()$currentContext() : 
  Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)

我想我明白为什么这不起作用,那么问题是该怎么办?我发现 isolate() 在响应式(Reactive)上下文之外工作,但我不确定这是否是实现这种逻辑的正确方法。

我最终尝试基于不需要操作按钮的观察者进行多个输入。这是可能的还是我在这里滥用了这个概念?

最佳答案

从观察语句中删除Query$A。观察语句将根据其中包含的依赖项确定何时运行。

使用您的应用程序的最小工作示例:

library(shiny)

ui <- fluidPage(
    
    selectInput("QueryScheme",            "QueryScheme",           choices = sample(1:10, 3)),
    selectInput("SortedSchemes",          "SortedSchemes",         choices = sample(1:10, 3)),
    actionButton("SomeActionButton",      "SomeActionButton"),
    actionButton("UnrelatedActionButton", "UnrelatedActionButton")
    
)

server <- function(input, output, session) {
    
    #Reactive Values
    Query <- reactiveValues(A = NULL, B = NULL)
    
    #Observe Some Action Button (runs once when button pressed)
    observeEvent(input$SomeActionButton,{
        Query$A <- sample(1:10, 3)
        Query$B <- sample(1:10, 3)
        updateSelectizeInput(session, "QueryScheme", choices =  Query$B)
    })

    #Observe reactive value Query$B (runs once when Query$B changes)
    observe({
        showNotification("Query$B has changed, running Observe Function")
        QueryNames <- sort(Query$B)
        updateSelectizeInput(session, "SortedSchemes", choices = QueryNames)
    })
    
    #Observe Unrelated Action Button (runs once when button pressed) note that it won't trigger the above observe function
    observeEvent(input$UnrelatedActionButton,{
        showNotification("UnrelatedActionButton Pressed")
    })
    
}

shinyApp(ui, server)

关于r - Shiny :在reactiveValues()上观察(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64759368/

相关文章:

system.reactive - 为什么我需要在完成后处理订阅?

r - 如何访问存储在包中的 R markdown

r - Shinyapps.io 将所有数值数据转换为 NA

java - next() 与 Single() 哪个有效?

r - R 中的 react 性问题 - 您尝试做一些只能从 react 性消费者内部完成的事情

r - 如何将工具提示添加到 R shiny 中的数据表行名?

angular - 如何使用 Angular 8 中的 react 形式将模型绑定(bind)到形成构建器

r - 在 R 中与 biomart 循环

r - 使用 InfoMap 算法进行社区检测,产生一个庞大的模块

r - `write.dbf` 因类 `tbl_df` 的对象而失败