声明依赖于值而不是另一个变量的最佳方法是什么。这里的想法是,如果值没有改变,它不应该触发进一步的重新计算。例如:
# In the code below we are displaying the result of an input divided by
# ten using integer division. As a result, many different values result in
# the same value to be displayed and should not trigger re-rendering (ideally)
# However, the obvious implementation using reactive(...) does re-render.
# reactiveValues(...) seems to provide a solution.
library(shiny)
out <- function(...) cat(file = stderr(), ..., "\n")
server <- function(input, output) {
vals <- reactiveValues()
tenth <- function() {
result <- input$n %/% 10
out('Computing tenth:', input$n, '->', result)
result
}
observeEvent(input$n, {
result <- tenth()
out("Updating vals$tenth:", input$n, '->', result)
vals$tenth <- result
})
output$tenth.val <- renderText({
result <- vals$tenth
out("Rendering tenth.val:", result)
result
})
tenth.reactive <- reactive({
result <- tenth()
out("Executing tenth.reactive", result)
result
})
output$tenth.ref <- renderText({
result <- tenth.reactive()
out("Rendering tenth.ref:", result)
result
})
}
ui <- fluidPage(
sliderInput("n", NULL, min = 0, max = 20, value = 3),
'One tenth of the above value is',
tags$ul(
tags$li(textOutput('tenth.val', inline = T), '(val)'),
tags$li(textOutput('tenth.ref', inline = T), '(ref)')
)
)
shinyApp(ui = ui, server = server)
当从9到10滑动时,stderr输出为:
Computing tenth: 9 -> 0
Updating vals$tenth: 9 -> 0
Computing tenth: 9 -> 0
Executing tenth.reactive 0
Rendering tenth.ref: 0
Computing tenth: 10 -> 1
Updating vals$tenth: 10 -> 1
Computing tenth: 10 -> 1
Executing tenth.reactive 1
Rendering tenth.ref: 1
Rendering tenth.val: 1
请注意Rendering tenth.val
只出现一次。即,使用无效值的方法可避免在输出值未更改时重新呈现。但是Rendering tenth.ref
出现两次,因为失效级联没有注意到值没有改变。
使用reativeValues()
是实现此效果的最佳方法吗? (对我而言似乎有点圆了。)