为什么 React({ }) 不依赖于不断变化的输入?

问题描述 投票:0回答:1

在下面的 Shiny 应用程序代码中,我期望当用户单击数据表中的新行时执行打印行。当我这样做时,textOutput 按预期通过 input$table_rows_selected 更新所选行。但为什么会改变<- reactive({ }) not take a dependency on changes to input$table_rows_selected and trigger the print message?

我看到它可以与observe({})一起使用,但最终我想使用一个在不同地方反应返回的值(例如这里的return和return2)。

library(shiny)
library(DT)

ui <- fluidPage(

     DT::DTOutput("table"),
     
     textOutput("selected"),
     
     textOutput("return"),
     
     textOutput("return2")

)

server <- function(input, output) {

    output$table <- DT::renderDataTable({
        data.frame(a = 1:3, b = 4:6)
    }, selection = 'single')
    
    
    output$selected <- renderText({
        input$table_rows_selected
    })
    
    change <- reactive({
        input$table_rows_selected
        print("it changed!")
        "return"
    })
    
    output$return <- renderText({
        isolate(change())
    })
    
    output$return2 <- renderText({
        paste0(isolate(change()), "_2")
    })
    
    
}

# Run the application 
shinyApp(ui = ui, server = server)
r shiny dt
1个回答
0
投票

您的代码有 2 个问题:

  • a
    reactive
    只是一个函数,因此它的返回值是
    reactive
    中生成的最后一个值 -> 你需要将
    input$table_rows_selected
    最后
  • isolate(change())
    表示
    reactives
    不依赖于
    input$table_rows_selected
    -> 删除
    isolate
library(shiny)
library(DT)

ui <- fluidPage(
  
  DT::DTOutput("table"),
  
  textOutput("selected"),
  
  textOutput("return"),
  
  textOutput("return2")
  
)

server <- function(input, output) {
  
  output$table <- DT::renderDataTable({
    data.frame(a = 1:3, b = 4:6)
  }, selection = 'single')
  
  
  output$selected <- renderText({
    input$table_rows_selected
  })
  
  change <- reactive({
    print("it changed!")
    input$table_rows_selected
  })
  
  output$return <- renderText({
    change()
  })
  
  output$return2 <- renderText({
    paste0(change(), "_2")
  })
  
  
}

# Run the application 
shinyApp(ui = ui, server = server)
© www.soinside.com 2019 - 2024. All rights reserved.