【问题标题】:update shiny input with observeEvent使用 observeEvent 更新闪亮的输入
【发布时间】:2019-06-07 22:43:06
【问题描述】:

我希望用户定义一个初始数值,然后在每次单击操作按钮时按设定的数量更新(即添加)。我使用 reactiveVal 尝试进行此更新,但我得到了可怕的 Operation not allowed without an active reactive context 错误。我很困惑,因为我认为使用 reactiveVal 是在反应式表达式中做某事,但显然我错了。

我已查找相关问题/文章/教程,但一无所获。非常感谢任何建议。请让我知道是否有更好的方法来完成这项任务,即我是否应该使用不同的功能或方法。

我的代码的精简版本如下:

library(shiny)

ui <- fluidPage(

    ## initilize the value
    numericInput('init.i','initial i',10),

    ## click this button to add one to the initial value
    actionButton("run","Run"),

    ## output the current count
    textOutput("cur.i")

)

server <- function(input,output) {

    ## define the current value according to the inital value
    i <- reactiveVal({
        input$init.i ## this line fails
        ##1 ## this line doesn't fail but value always initializes at 1 
    })

    observeEvent(input$run, {
        ## make a new value by adding 1 to the current value
        new.i <- i() + 1
        ## update the value
        i(new.i)

        output$cur.i <- renderText({
            ## print the current value
            i()
        })
    })

}

shinyApp(ui=ui,server=server)

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    以下作品。正如闪亮向您报告的那样,您正在尝试做的事情是不允许的。这是 i() 的初始化,您使用 input$init.i 需要反应上下文。

    可以通过在您想要的初始值 (input$init.i) 上创建另一个 observeEvent 来实现想要的效果,并将您的反应值设置为该值。

    library(shiny)
    ui <- fluidPage(
    
      ## initilize the value
      numericInput('init.i','initial i', 10),
    
      ## click this button to add one to the initial value
      actionButton("run","Run"),
    
      ## output the current count
      textOutput("cur.i")
    
    )
    server <- function(input,output) {
    
      ## Define the reactive value (with no 'inital' value)
      i <- reactiveVal()
    
      ## Set i() based on "initialize" input widget
      observeEvent(input$init.i, { 
        i(input$init.i)
      })
    
      observeEvent(input$run, {
        ## make a new value by adding 1 to the current value
        new.i <- i() + 1
        ## update the value
        i(new.i)
       })
    
      output$cur.i <- renderText({
        i()
      })
    }
    shinyApp(ui = ui, server = server)
    

    此外,无需将renderText 嵌套在observeEvent 中。

    【讨论】:

    • 太棒了!感谢您的快速回复和乐于助人的 cmets!
    猜你喜欢
    • 2020-05-24
    • 2021-12-05
    • 1970-01-01
    • 2020-11-03
    • 2018-05-02
    • 2022-11-29
    • 2020-09-24
    • 1970-01-01
    • 2021-08-16
    相关资源
    最近更新 更多