2017-08-03 4 views
2

次の例では、テキストが先頭に表示されません。 "show"ボタンをクリックすると、テキストが表示されます。私が「隠す」ボタンをクリックすると、何も起こりません。 実際、 "textis $ visible"変数は常に正しい値を持ちますが、observeEvent funktionのif文は、最初のボタンをクリックした後にのみ計算されると思います。なぜobserveEventはコンテンツを再評価しないのですか?

observeEventにif文の再評価を強制する方法はありますか?あるいは、サーバー部分でコードを実行してから光沢を止めてもう一度やり直す方法は他にあります(実際にはif文の中に関数呼び出しがたくさんあり、テキストを隠して表示するだけではありません)

library(shiny) 

ui <- fluidPage(

actionButton(inputId="show","show"), 
actionButton(inputId="hide","hide"), 

textOutput(outputId = "some_text") 
) 


server <- function(input, output) { 

    textis<-reactiveValues(visible=FALSE) 

observeEvent(input$show, 
      textis$visible<-TRUE) 

observeEvent(input$hide, 
      textis$visible<-FALSE) 

observeEvent(textis$visible , if(textis$visible){ 
    output$some_text<-renderText({"this is some text"}) 
})} 

shinyApp(ui = ui, server = server) 

答えて

1

observeEvent式は、イベント式の値が変更されるたびに評価されます。しかし、上記のコードでは、textis$visibleが変更された場合、オブザーバーはtextis$visibleがtrueの場合に実行する指示しかありません。以下のコードスニペットでは、testis$visibleが真でない場合に、オブザーバに実行するアクションを与えるためにelse{...}を使用しました。だから、

observeEvent(textis$visible , if(textis$visible){ 
    output$some_text<-renderText({"this is some text"}) 
    } else {output$some_text<-renderText({''}) } 
)} 

、あなたのアプリに上記else句を貼り付けた場合に非表示ボタンがクリックされたときに、出力some_textが消えます。オブザーバーでレンダリング要素を(そしてそれが不要である)に置くには非常に良い習慣ではありません

library(shiny) 

ui <- fluidPage(

    actionButton(inputId="show","show"), 
    actionButton(inputId="hide","hide"), 
    textOutput(outputId = "some_text") 
) 

server <- function(input, output) { 

    textis <- reactiveVal(F) 
    observeEvent(input$show,{textis(T)}) 

    observeEvent(input$hide,{textis(F)}) 

    result <- eventReactive(textis(),{ 
    if(!textis()){ 
     return() 
    } 
    "this is some text" 
    }) 

    output$some_text<-renderText({result()}) 
} 

shinyApp(ui = ui, server = server) 
+0

解き私のこの種の問題。しかし、実際のアプリケーションでは、server.Rのコードの一部を実行しないようにしたいので、特定の値がfalseになると、すでに実行されたものを表示しません。これはログアウト機能のようなもので、他のコンピュータユーザーはあなたが計算したものを見ていません。多分Rセッションを再開する方法はありますか?光沢のあるアプリをリセットするための –

+0

私は良い答えを見つけました: https://stackoverflow.com/questions/25062422/restart-shiny-session –

0

はこのような何かを試してみてください。また、reactValueが1つしかないので、reactiveVal()を使用することもできます(下の例を参照)。その値をtext_visible()で呼び出し、それをtext_visible(new_value)で更新することができます。

の作業例:

library(shiny) 

ui <- fluidPage(

    actionButton(inputId="show","show"), 
    actionButton(inputId="hide","hide"), 
    textOutput(outputId = "some_text") 
) 


server <- function(input, output) { 

    text_visible<-reactiveVal(TRUE) 

    observeEvent(input$show, 
       text_visible(TRUE)) 

    observeEvent(input$hide, 
       text_visible(FALSE)) 

    output$some_text<-renderText({ 
    if(text_visible()) 
     return("this is some text") 
    else 
     return("") 
    }) 
} 

    shinyApp(ui = ui, server = server) 
関連する問題