【问题标题】:Error in .getReactiveEnvironment()$currentContext() while using reactive output in reactiveValues function在 reactiveValues 函数中使用反应输出时 .getReactiveEnvironment()$currentContext() 出错
【发布时间】:2019-06-06 00:35:36
【问题描述】:

我正在尝试获取一个依赖于响应式的 reactiveValue。在实际代码中(这是一个非常简化的版本),我以交互方式加载数据集。按下按钮时它会改变(prevBtn/nextBtn)。我需要知道数据集中的行数,用它来绘制不同颜色的数据点。

问题:为什么我不能在 reactiveValues 函数中使用反应式 ro()?

为了理解:为什么错误是“You tried to do something that can only be done from inside a reactive expression or observer.”,尽管 ro() 是在反应式上下文中使用的。

这个错误肯定是vals()导致的,其他的我已经检查过了。

代码:

library(shiny)
datasets <- list(mtcars, iris, PlantGrowth)
ui <- fluidPage(
    mainPanel(
        titlePanel("Simplified example"),
        tableOutput("cars"),
        actionButton("prevBtn", icon = icon("arrow-left"), ""),
        actionButton("nextBtn", icon = icon("arrow-right"), ""),
        verbatimTextOutput("rows")
    )
)
server <- function(input, output) {
    output$cars <- renderTable({
        head(dat())
    })
    dat <- reactive({
        if (is.null(rv$nr)) {
            d <- mtcars
        }
        else{
            d <- datasets[[rv$nr]]
        }
    })
    rv <- reactiveValues(nr = 1)
    set_nr <- function(direction) {
        rv$nr <- rv$nr + direction
    }
    observeEvent(input$nextBtn, {
        set_nr(1)
    })
    observeEvent(input$prevBtn, {
        set_nr(-1)
    })
    ro <- reactive({
        nrow(dat())
    })
    output$rows <- renderPrint({
        print(paste(as.character(ro()), "rows"))
    })
    vals <- reactiveValues(needThisForLater = 30 * ro())
}
shinyApp(ui = ui, server = server)

.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.)

【问题讨论】:

    标签: r shiny shiny-reactivity


    【解决方案1】:

    我想你想要

    vals <- reactiveValues(needThisForLater = reactive(30 * ro()))
    

    并非reactiveValues 列表中的所有内容都被假定为反应式。它也是存储常量值的好地方。因此,由于它试图评估您在运行时传递的参数并且您没有在反应式环境中调用该行,因此您会收到该错误。因此,只需将其包装在对 reactive() 的调用中,您就可以为要调用的 ro() 提供一个响应式环境。

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 2018-08-20
      • 2020-06-14
      • 2016-01-13
      • 2020-06-05
      • 2017-06-13
      • 2014-09-06
      • 2019-07-19
      • 2020-02-16
      相关资源
      最近更新 更多