開始使用免費開始

使用 isolate() 停止反應

一般來說,只要讀取反應值,就足以建立關聯;當該反應值改變時,呼叫它的運算式就會重新執行。isolate() 函式可讓運算式讀取反應值,但在其值變動時不會觸發重新執行。

在這個練習中,你會使用 isolate() 來停止反應流程。

本練習屬於課程

使用 R 的 Shiny 建立網頁應用程式

檢視課程

練習說明

  • 更新伺服器端程式碼,讓文字輸出只在使用者變更身高或體重時更新,而不要在變更姓名時更新。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

ui <- fluidPage(
  titlePanel('BMI Calculator'),
  sidebarLayout(
    sidebarPanel(
      textInput('name', 'Enter your name'),
      numericInput('height', 'Enter your height (in m)', 1.5, 1, 2, step = 0.1),
      numericInput('weight', 'Enter your weight (in Kg)', 60, 45, 120)
    ),
    mainPanel(
      textOutput("bmi")
    )
  )
)

server <- function(input, output, session) {
  rval_bmi <- reactive({
    input$weight/(input$height^2)
  })
  output$bmi <- renderText({
    bmi <- rval_bmi()
    # MODIFY CODE BELOW: 
    # Use isolate to stop output from updating when name changes.
    paste("Hi", input$name, ". Your BMI is", round(bmi, 1))
  })
}

shinyApp(ui = ui, server = server)
編輯並執行程式碼