【问题标题】:How to render more than once when using observeEvent in shiny?在闪亮中使用observeEvent时如何多次渲染?
【发布时间】:2018-08-17 21:28:07
【问题描述】:

我在 R 中使用 shiny 并希望在 server.R 中使用 observeEvent 时多次渲染

我不明白为什么这不起作用:

library(shiny)

my_UI <- fluidPage(
  fluidRow(actionButton("test", "test")),
  fluidRow(textOutput("out"))
)

my_Server <- function(input, output) {
  observeEvent(input$test, {
    output$out <- renderText("waiting")
    Sys.sleep(2)
    output$out <- renderText("done")
  })
}

shinyApp(my_UI, my_Server)

我也试过了:

library(shiny)

my_UI <- fluidPage(
  fluidRow(actionButton("test", "test")),
  fluidRow(textOutput("out"))
)

my_Server <- function(input, output) {

  observeEvent(input$test, {
    output$out <- renderText("waiting")
  })
  observeEvent(input$test, {
    Sys.sleep(2)
    output$out <- renderText("done")
  })
}

shinyApp(my_UI, my_Server)

在这两种情况下,只呈现后一个消息... 我在这里做错了什么?谢谢!

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    我无法在一个观察事件中为每一行渲染提供解决方案,但如果您只想显示加载/计算进度,您可以使用

    withProgress()

    所以应用可以是这样的:

    library(shiny)
    
    my_UI <- fluidPage(
      fluidRow(actionButton("test", "test")),
      fluidRow(textOutput("out"))
    )
    
    my_Server <- function(input, output) {
    
      observeEvent(input$test, {
        withProgress(
          message = 'Calculation in progress',
          detail = 'This may take a while...', value = 0, {
            incProgress(1/2, message = "Step 1")
            Sys.sleep(2)
            # Do some stuff, load, calculate, etc
            incProgress(1/2, message = "Step 2")
          })
      })
    }
    
    shinyApp(my_UI, my_Server)
    

    【讨论】:

    • 谢谢。所以这是shiny 的限制...尽管withprogress() 对我来说是一个公平的解决方法=]
    【解决方案2】:

    您不能对 Shiny 执行此操作,因为只会使用最新的输出值。

    您可以使用 javascript 来完成,但您可能有更好的选择,即 withProgress as feniw_fx 提及

    library(shiny)
    my_UI <- fluidPage(
      tags$head(
        tags$script(
          "function test() {
          document.getElementById('out').innerHTML = 'waiting';
          setTimeout(function() {document.getElementById('out').innerHTML = 'done'}, 2000);}"
      )),
      fluidRow(actionButton("test", "test", onclick = "test()")),
      fluidRow(textOutput("out"))
    )
    
    my_Server <- function(input, output, session) {
    
    }
    
    shinyApp(my_UI, my_Server)
    

    【讨论】:

      猜你喜欢
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      • 1970-01-01
      • 1970-01-01
      • 2019-06-07
      • 1970-01-01
      相关资源
      最近更新 更多