gpt4 book ai didi

r - 如何重置 react 值?

转载 作者:行者123 更新时间:2023-12-02 19:30:27 24 4
gpt4 key购买 nike

重置单个 react 值只需通过 reactiveVal(NULL) 即可完成。但是,如何才能完全重置 reactiveValues()

虚拟应用程序包含我的一些方法来保留新鲜和干净的 react 值,但它们都没有真正做到我希望它们做的事情。此外,在观察 reactiveValues 时似乎有一种奇怪的行为。除非单击 Trigger 按钮,否则它们不会在清洁后触发 react 。当我检查他们的状态时,他们看起来很好。

library(shiny)
library(magrittr)

# UI ---------------------------------------------------------------------------
ui <- fluidPage(
actionButton("create", "Create"),
actionButton("reset", "Reset"),
actionButton("trigger", "Trigger"),
textOutput("out")
)

# Server -----------------------------------------------------------------------
server <- function(input, output, session) {

vals <- reactiveValues()
ids <- reactiveVal()
display <- reactiveVal()

# insert letter when clicked
observeEvent(input$create, {
id <- as.character(length(ids()))
vals[[id]] <- sample(LETTERS, 1)
ids(c(ids(), id))
})

observeEvent(input$reset, {
# Options to reset reactive Values -------------------------------------
vals <<- reactiveValues()
# vals <- NULL
for(i in names(vals)) vals[[i]] <- NULL # deletes content but not the names

# resetting reactiveVal() is easily done via NULL
ids(NULL)
display(NULL)
})

observe({
if(input$trigger) browser()
text <- reactiveValuesToList(vals) %>% paste(collapse = ", ")
display(text)
})

output$out <- renderText(display())
}

shinyApp(ui, server)

P.S.:该示例并未完全精简,因为我希望它反射(reflect)我的实际 react 链。

最佳答案

显然你不能完全取消 reactiveValues

看看:

Shiny: How to initialize empty reactiveValues with an actionButton?

shiny: How to update a reactiveValues object?

根据这两个问题的答案,作为一种解决方法,可以将值保存在 reactiveValues 对象的列表中,您的代码将如下所示:

library(shiny)
library(magrittr)

# UI ---------------------------------------------------------------------------
ui <- fluidPage(
actionButton("create", "Create"),
actionButton("reset", "Reset"),
actionButton("trigger", "Trigger"),
textOutput("out")
)

# Server -----------------------------------------------------------------------
server <- function(input, output, session) {
# initialize vals with a list
vals <- reactiveValues('foo' = list())
ids <- reactiveVal()
display <- reactiveVal()

observeEvent(input$create, {
id <- as.character(length(ids()))
# add values to the list
vals$foo[[id]] <- sample(LETTERS, 1)
ids(c(ids(), id))
})

observeEvent(input$reset, {
# reset the list
vals$foo <- NULL
ids(NULL)
})

observe({
# if(input$trigger) browser()
text <- reactiveValuesToList(vals) %>% paste(collapse = ", ")
display(text)
})

output$out <- renderText({
text <- vals$foo %>% paste(collapse = ", ")
display(text)
display()
})
}

shinyApp(ui, server)

关于r - 如何重置 react 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61887112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com