簡體   English   中英

Shiny:為什么 updateSliderInput 只工作一次?

[英]Shiny: Why updateSliderInput works only one time?

我正在嘗試編寫 Shiny 應用程序,一旦我在按下按鈕時執行任意代碼,它將動態更新 slider 輸入最大值:

library(shiny)

ui <- fluidPage(

    # Sidebar with a slider input for number of bins 
    sidebarLayout(
        sidebarPanel(
            sliderInput("bins",
                        "Number of bins:",
                        min = 1,
                        max = 50,
                        value = 30),
            actionButton(inputId ="refresh", label = 'boom')
        ),

        # Show a plot of the generated distribution
        mainPanel(
           plotOutput("distPlot")
        )
    )
)

# Define server logic required to draw a histogram
server <- function(input, output, session) {
    
    counter <- reactiveValues(c = nrow(faithful))

    observeEvent(input$refresh, {
        
        faithful <- faithful[-1:-10, ]
        counter$c <- nrow(faithful)
        updateSliderInput(session, "bins", min = 1, max = counter$c, value = counter/2)
    })
    
    
    output$distPlot <- renderPlot({
        # generate bins based on input$bins from ui.R
        x    <- faithful[, 2]
        bins <- seq(min(x), max(x), length.out = input$bins + 1)

        # draw the histogram with the specified number of bins
        hist(x, breaks = bins, col = 'darkgray', border = 'white')
    })
}

# Run the application 
shinyApp(ui = ui, server = server)

不幸的是,slider 輸入更新只能工作一次! 文檔示例建議使用observe()構造觀察一些反應值,但是我希望在使用observeEvent()時這樣的功能也應該起作用這里有什么問題?

感謝你的幫助!

這里的問題不是updateSliderInput ,而是counter不是反應式的,因此它在應用程序內不是持久的。 只需將其轉換為本示例中的反應式,它就可以正常工作。

library(shiny)

ui <- fluidPage(
  
  # Sidebar with a slider input for number of bins 
  sidebarLayout(
    sidebarPanel(
      sliderInput("bins",
                  "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30),
      actionButton(inputId ="refresh", label = 'boom')
    ),
    
    # Show a plot of the generated distribution
    mainPanel(
      plotOutput("distPlot")
    )
  )
)

# Define server logic required to draw a histogram
server <- function(input, output, session) {
  
  counter <- reactiveValues(c = 10)
  
  observeEvent(input$refresh, {
    counter$c <- counter$c + 10
    updateSliderInput(session, "bins", min = 1, max = counter$c, value = counter$c/2)
  })
  
  
  output$distPlot <- renderPlot({
    # generate bins based on input$bins from ui.R
    x    <- faithful[, 2]
    bins <- seq(min(x), max(x), length.out = input$bins + 1)
    
    # draw the histogram with the specified number of bins
    hist(x, breaks = bins, col = 'darkgray', border = 'white')
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM