我有一个带有 DT 数据表的闪亮应用程序,其中包括 selectInputs。如果我在第 1 页上进行选择,更改页面,然后返回到第 1 页,则选择将被重置。更改页面后如何保留我的选择?
编辑
设置
server = FALSE
在此示例中有效,但由于其他原因,我需要在实际应用程序中使用服务器端处理(例如,使用 DT::datatableProxy()
和 DT::replaceData()
),因此我需要保留默认的 server = TRUE
。
library(shiny)
library(DT)
shinyApp(
ui = fluidPage(
DT::dataTableOutput("mytable")
),
server = function(input, output, session) {
df <- data.frame(
Col1 = sapply(1:20, function(i) as.character(selectInput(
inputId = paste0("input", i),
label = NULL,
choices = letters[1:3]
)))
)
output$mytable <- DT::renderDataTable({
DT::datatable(
data = df,
selection = "none",
rownames = F,
escape = F
)
})
}
)
我假设您已经知道如何实现这一点,但我回答是为了防止其他人遇到类似的问题:
library(shiny)
library(DT)
shinyApp(
ui = fluidPage(
DT::dataTableOutput("mytable")
),
server = function(input, output, session) {
r <- reactiveValues(df = NULL, inputs = NULL)
output$mytable <- DT::renderDataTable({
DT::datatable(
data = r$df,
selection = "none",
rownames = F,
escape = F,
options = list(preDrawCallback = JS("function() {Shiny.unbindAll(this.api().table().node());}"),
drawCallback = JS("function() {Shiny.bindAll(this.api().table().node());}"))
)
})
observe({
r$inputs <- lapply(1:20, function(i) {
if (is.null(input[[paste0("input", i)]])) {
letters[1]
} else {
input[[paste0("input", i)]]
}
})
r$df <- data.frame(
Col1 = sapply(1:20, function(i) as.character(selectInput(
inputId = paste0("input", i),
label = NULL,
choices = letters[1:3],
selected = r$inputs[i]
)))
)
})
}
)