0

我有一个较大的闪亮应用程序,其中多个元素发生变化reactiveVal。现在我想移植应用程序以使用闪亮的模块,以便能够更适当地对其进行测试。但是我无法访问在服务器函数中定义的反应值。

MWE

到目前为止,一个突出我思考过程的简单应用程序是这个计数器应用程序。该应用程序包含两个模块:counterdisplay

  • counter单击按钮时增加反应计数器值
  • display监视计数器并将其输出显示到文本字段

应用程序的主要部分是一个名为 的“中心”反应值counter_reactive,它保存当前计数。该值由模块元素设置counter和读取。display

library(shiny)

######################
# Counter Module
counter_UI <- function(id) {
  ns <- NS(id)
  tagList(
    actionButton(ns("button"), "Increase Count")
  )
}
counter <- function(input, output, session) {
  observeEvent(input$button, {
  counter_reactive(counter_reactive() + 1)
    cat("Increase Counter by 1 to", counter_reactive(), "\n")
  })
}

######################
# Display Module
display_UI <- function(id) {
  ns <- NS(id)
  tagList(
    verbatimTextOutput(ns("text_output"))
  )
}
display <- function(input, output, session) {
  observe({
    cat("Print Value of Counter\n")
    output$text_output <- renderText(sprintf("Counter is now %i", counter_reactive()))
  })
}

######################
# Rest of the Shiny App
ui <- fluidPage(
  counter_UI("counter1"),
  display_UI("display1")
)

server <- function(input, output, session) {
  # Note that counter_reactive is defined inside the "global" server function, 
  # as multiple modules should read and write to it. 
  counter_reactive <- reactiveVal(0)
  
  callModule(counter, "counter1")
  callModule(display, "display1")
}

shinyApp(ui, server)

但是,此应用程序会引发错误Warning: Error in counter_reactive: could not find function "counter_reactive"。任何想法如何获取/更改模块内的反应值?

4

1 回答 1

1

Rubber-Ducky-Debugging(又名 SO-Question Writing Debugging)来救援,这有效:

像这样简单地将反应值传递给函数

counter <- function(input, output, session, counter_reactive) {
  observeEvent(input$button, {
    counter_reactive(counter_reactive() + 1)
    cat("Increase Counter by 1 to", counter_reactive(), "\n")
  })
}

display <- function(input, output, session, counter_reactive) {
  observe({
    cat("Print Value of Counter\n")
    output$text_output <- renderText(sprintf("Counter is now %i", counter_reactive()))
  })
}

server <- function(input, output, session) {
  
  counter_reactive <- reactiveVal(0)
  
  callModule(counter, "counter1", counter_reactive)
  callModule(display, "display1", counter_reactive)
}
于 2020-08-26T09:00:44.360 回答