闪亮的反应式表达和动作按钮

时间:2014-12-04 05:37:27

标签: r shiny

在下面显示的闪亮代码中,无论输入文本是否发生变化,每次单击按钮时都会刷新输出(随机数更改)。如何编写,以便仅在单击按钮并且输入不同时才刷新输出?

require(shiny)

ui <- shinyUI(
    navbarPage("Test",
        tabPanel("Panel1",
            fluidRow(
                column(offset=2, width=2,
                    textInput("text", label=h6("Input"), value="test123"),
                    br(),
                    actionButton("actionClick", label="Click")
                ),
                column(offset=1, width=2,
                    h6("Output"),
                    verbatimTextOutput(outputId="sessionId")
                )
            )
        )
    )
)

server <- function(input, output, session) {

    session <- reactive({
        input$actionClick

        isolate({
            return(input$text)
        })
    })

    output$sessionId <- renderText({paste(session(),runif(1))})
}

shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:2)

使用缓存变量可以解决此问题:

require(shiny)

ui <- shinyUI(
    navbarPage("Test",
        tabPanel("Panel1",
            fluidRow(
                column(offset=2, width=2,
                    textInput("text", label=h6("Input"), value="test123"),
                    br(),
                    actionButton("actionClick", label="Click")
                ),
                column(offset=1, width=2,
                    h6("Output"),
                    verbatimTextOutput(outputId="sessionId")
                )
            )
        )
    )
)

server <- function(input, output, session) {
    cacheText <- "NULL"
    cacheNumber <- "0"
    session <- reactive({
        input$actionClick

        isolate({
            return(input$text)
        })
    })

    output$sessionId <- renderText({

        if(cacheText != session()) {
            cacheText <<- input$text
            cacheNumber <<- runif(1)
            return(paste(session(),cacheNumber))


        } else {
            return(paste(cacheText, cacheNumber))
        }



    })
}

shinyApp(ui = ui, server = server)