简体   繁体   English

在Shiny中使用observeEvent时,如何多次渲染?

[英]How to render more than once when using observeEvent in shiny?

I am using shiny in R and want to render more than once when using observeEvent in server.R 我使用shiny的R和想用的时候渲染不止一次observeEvent在server.R

I don't understand why this does not work: 我不明白为什么这行不通:

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)

I also tried: 我也尝试过:

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)

In both cases, only the latter message is rendered... What am I doing wrong here? 在这两种情况下,仅呈现后一个消息……我在这里做错了什么? Thanks! 谢谢!

I can't give you solution for each line render in one observeEvent, but if you just want show loading/calculation progress, you can use 我无法在一个observeEvent中为每一行渲染提供解决方案,但是如果您只想显示加载/计算进度,则可以使用

withProgress() withProgress()

so app can be like this: 所以应用程序可以像这样:

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)

You can't do this with Shiny, because only the latest output value will be used. 您无法使用Shiny进行此操作,因为将仅使用最新的输出值。

You can do it with javascript, but you have probably better options, ie withProgress as feniw_fx mentionned 你可以用JavaScript做,但你可能有更好的选择,即withProgress为feniw_fx mentionned

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM