【问题标题】:Updating reactiveValues from initialized state从初始化状态更新 reactiveValues
【发布时间】:2021-06-03 20:04:04
【问题描述】:

我想创建动态数量的控件(使用renderUI)并让这些控件更新reactiveValues 对象。但是,当应用加载时,reactiveValues 对象似乎是 NULL,因此所有值都会更新为 NULL,而不是所需的初始状态。

library(shiny)

ui <- fluidPage(
    uiOutput("controls"),
    tableOutput("result")
)


server <- function(input, output) {
    
    # Initial state of reactive values
    rv <- reactiveValues(
        my_table = dplyr::starwars %>%
            select(name) %>%
            mutate(checkbox = TRUE) %>%
            sample_n(10)
    )
    
    # Render the dynamic UI 
    output$controls <- renderUI({
        
        lapply(1:nrow(rv$my_table), function(i) {
            fluidRow(
                column(1, checkboxInput(paste0('checkbox',i), value = rv$my_table[[i,"checkbox"]], label = NULL)),
                column(4, textInput(paste0('name',i), value = rv$my_table[[i,"name"]], label = NULL, width = '600'))
            )
        })
        
    })
    
    # Update state of reactive values
    observe({
        checkboxes <- unlist(lapply(1:nrow(rv$my_table), function(i) {
            input[[paste0("checkbox", i)]]
        }))
        print(checkboxes) # It seems on load as NULL first before the rv$my_table loads
        names <- unlist(lapply(1:nrow(rv$my_table), function(i) {
            input[[paste0("name", i)]]
        }))
        # rv$my_table['checkbox'] <- checkboxes # Uncomment for desired updates
        # rv$my_table$name <- names # Uncomment for desired updates
    })
    
    # Render output
    output$result <- renderTable({
        rv$my_table %>%
            filter(checkbox)
    })
    
}

shinyApp(ui = ui, server = server)

【问题讨论】:

    标签: r shiny shiny-reactivity


    【解决方案1】:

    这是您在 UI 中正确初始化之前收集的输入(如 input$checkbox1 等)。

    一种快速的解决方法可能是将req(input$checkbox1) 放在observe 块的开头,这样它就不会尝试读取它们,直到输入已填充到 UI 中。

    【讨论】:

    • 这种方法有效,但是默认是input$checkbox1 == FALSE。如果我取消选中checkbox1,那么它就不起作用了。有没有办法只要求 input$checkbox1 已初始化?作为一种解决方法,我添加了一个actionButton 并将observer 变成了一个observeEvent
    • req(!is.null(input$checkbox1)) 会更好。
    猜你喜欢
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 2018-08-22
    • 2021-08-29
    • 2020-08-30
    • 2023-03-08
    相关资源
    最近更新 更多