是否可以通过编辑 DT::DataTable 来更新响应式(Reactive)数据源?以下代码基于 this code随着变化,x 成为 react 性的。当尝试更改observeEvent 中的x 时,问题就开始了。
让 x react 的目的是我打算从外部数据库中获取它,然后将 DT::DataTable 的编辑写回数据库,以便它与用户看到的内容保持同步(我很好那 - 这不是问题的一部分)。
library(shiny)
library(DT)
shinyApp(
ui = fluidPage(
DTOutput('x1')
),
server = function(input, output, session) {
x = reactive({
df <- iris
df$Date = Sys.time() + seq_len(nrow(df))
df
})
output$x1 = renderDT(x(), selection = 'none', editable = TRUE)
proxy = dataTableProxy('x1')
observeEvent(input$x1_cell_edit, {
info = input$x1_cell_edit
str(info)
i = info$row
j = info$col
v = info$value
# problem starts here
x()[i, j] <<- isolate(DT::coerceValue(v, x()[i, j]))
replaceData(proxy, x(), resetPaging = FALSE) # important
})
}
)
最佳答案
我不确定我是否正确理解您,但也许这个解决方案可能对您有所帮助。我将您的 react 更改为reactiveValues 对象,并删除了replaceData 行。
library(shiny)
library(DT)
shinyApp(
ui = fluidPage(
DTOutput('x1'),
verbatimTextOutput("print")
),
server = function(input, output, session) {
x = reactiveValues(df = NULL)
observe({
df <- iris
df$Date = Sys.time() + seq_len(nrow(df))
x$df <- df
})
output$x1 = renderDT(x$df, selection = 'none', editable = TRUE)
proxy = dataTableProxy('x1')
observeEvent(input$x1_cell_edit, {
info = input$x1_cell_edit
str(info)
i = info$row
j = info$col
v = info$value
# problem starts here
x$df[i, j] <- isolate(DT::coerceValue(v, x$df[i, j]))
})
output$print <- renderPrint({
x$df
})
}
)
关于R Shiny DT - 用 react 编辑表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50470097/