【发布时间】: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