反应性值应在何时更新

时间:2019-04-08 19:53:44

标签: r shiny

我是Shiny的新手,我认为我不了解一些基本原理。如何使我的变量更新?

variable1和output $ add都是反应性的,那么为什么按下按钮后它们在屏幕上不改变,以及如何使它们改变?

library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

  # Show a plot of the generated distribution
  mainPanel(
    textInput("inserted", "Insert a number"),
    textOutput("written"),
    textOutput("added"),
    actionButton("button1", "Push me")
  )
)

# Define server logic required to draw a histogram
server <- function(input, output) {

   variable1 <- reactive({
     as.numeric(input$inserted)
   })

   assign15tovar <- function() {
     variable1 <<- reactive({
       15
     })
   }

   observeEvent(input$button1, {
     assign15tovar()
   })

   output$written <- variable1
   output$added <- reactive({
     variable1() + 10
   })
}

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

代码只是我的实际应用中我的问题的一个示例,但是解决这个问题应该有所帮助。

1 个答案:

答案 0 :(得分:0)

我认为这是获得所需行为的最简单方法

True

通常,您不能手动设置反应性元素的值,因此需要专门用于设置其值的server <- function(input, output) { variable1 <- reactiveVal(0) observeEvent(input$inserted, { variable1(as.numeric(input$inserted)) }) assign15tovar <- function() { variable1(15) } observeEvent(input$button1, { assign15tovar() }) output$written <- renderText({variable1()}) output$added <- renderText({variable1() + 10}) } 。在这种情况下,reactiveVal返回当前值,而variable1()将设置一个新值。然后在这种情况下,我们需要观察文本框进行更改。

请注意,您的输出语句不正确。通常,您需要某种类型的variable1(newval)函数。通常,您通常不直接分配给他们。