我正在阅读有关闪亮反应式编程的所有内容.我有点困惑.以下所有工作但首选方法是什么?为什么?显然,下面的示例很简单,但是在使用任何方法创建更大的应用程序时,我会遇到麻烦吗?
我一直倾向于倾向于服务器代码#1中的风格.原因是,我能够打破if语句.对我来说,这似乎更具可读性.同样,下面的简单示例并不是非常复杂,但您可以很容易地想象服务器代码2和服务器代码3如何通过大量嵌套的if/if else语句变得非常混乱.
UI代码
library(shiny)
ui <- fluidPage(
selectInput(inputId = 'choice',
label = 'Choice',
choice = c('Hello','Goodbye'),
selected = c('Hello')
),
textOutput('result')
)
Run Code Online (Sandbox Code Playgroud)
服务器代码1
server <- function(input,output,session)({
text <- reactiveValues()
observe({
if (input$choice == 'Hello') {
text$result <- 'Hi there'
}
})
observe({
if (input$choice == 'Goodbye') {
text$result <- 'See you later'
}
})
output$result <- renderText({
text$result
})
})
shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)
服务器代码2
server <- function(input,output,session)({
getStatus <- reactive({
if (input$choice == 'Hello') {
'Hi …Run Code Online (Sandbox Code Playgroud) 在Shiny教程中,有一个例子:
fib <- function(n) ifelse(n<3, 1, fib(n-1)+fib(n-2))
shinyServer(function(input, output) {
currentFib <- reactive({ fib(as.numeric(input$n)) })
output$nthValue <- renderText({ currentFib() })
output$nthValueInv <- renderText({ 1 / currentFib() })
})
Run Code Online (Sandbox Code Playgroud)
我不知道如何reactive缓存这些值.它内部是否做了类似的事情return(function() cachedValue)?现在我想知道我能不能这样做?
fib <- function(n) ifelse(n<3, 1, fib(n-1)+fib(n-2))
shinyServer(function(input, output) {
currentFib <- reactiveValues({ fib(as.numeric(input$n)) })
output$nthValue <- renderText({ currentFib })
output$nthValueInv <- renderText({ 1 / currentFib })
})
Run Code Online (Sandbox Code Playgroud) 我reactiveValues经常在 Shiny 中使用,因为它们比input和output对象更灵活。嵌套的reactiveValues 很棘手,因为任何孩子的任何变化也会触发与父母相关的反应。为了解决这个问题,我尝试制作两个不同的reactiveValues对象(不是同一个列表中的两个对象,而是两个不同的列表),它似乎正在工作。我找不到任何这样的例子,想知道它是否应该以这种方式工作。是否有任何可能因此出现的问题?
在这个应用程序中,有两个反应值对象 -reac1和reac2。他们每个人都与一个下拉,column1并column2分别。更改column1或column2与最新更新时间的反应值,更新的情节,并在打印的最新值reac1和reac2。
ui = fluidPage(
titlePanel("Multiple reactive values"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = "column1", "Reac1", letters, selected = "a"),
selectInput(inputId = "column2", "Reac2", letters, selected = "a")
),
mainPanel(
plotOutput("plot1")
)
)
)
server = function(input, output, session) {
reac1 <- reactiveValues(asdasd = 0)
reac2 <- reactiveValues(qweqwe = 0)
# If any inputs …Run Code Online (Sandbox Code Playgroud)