注销按钮(操作按钮)在以下脚本中不起作用。我需要知道它为什么不起作用?以及如何修复它?
仅供参考:当我从代码中取出USER$Logged <- FALSE
时,该按钮有效但我无法再登录,因为Logged
仍为TRUE
。
欣赏!
UI
ui2 <- function(){
tagList(tabPanel(""),
pageWithSidebar(
headerPanel(
""
),
sidebarPanel
(
actionButton("logout", "Logout")
),
mainPanel(tableOutput('aaa'))
)
)
}
ui1 <- function(){
tagList(h2("Hello", align = "center"),
div(id = "login",
wellPanel(textInput("userName", "Username"),
passwordInput("passwd", "Password"),
br(),actionButton("Login", "Log in"),
)
}
服务器
server = (function(input, output,session) {
USER <- reactiveValues(Logged=FALSE)
observe({
if (USER$Logged == FALSE) {
if (!is.null(input$Login)) {
if (input$Login > 0) {
Username <- isolate(input$userName)
Password <- isolate(input$passwd)
query <- sprintf({"
SELECT rowid
FROM users
WHERE username='%s' and password ='%s'"},
Username, Password, serialize=F)
db <- RSQLite::dbConnect(RSQLite::SQLite(), dbname="db.sqlite")
user <- RSQLite::dbGetQuery(db, query)
RSQLite::dbDisconnect(db)
if ( length(user$rowid)==1 ) {
USER$Logged <- TRUE
}
}
}
}
})
observe({
if (USER$Logged == FALSE)
{
output$page <- renderUI({div(class="outer",do.call(bootstrapPage,c("",ui1())))})
}
if (USER$Logged == TRUE)
{
output$page <- renderUI({div(class="outer",do.call(navbarPage,c(inverse=TRUE,title = paste("Welcome", isolate(input$userName)," !"),ui2())))})
print(ui)
}
})
observeEvent(input$logout, {
output$page <- renderUI({div(class="outer",do.call(bootstrapPage,c("",ui1())))})
USER$Logged <- FALSE
})
})
生成小型数据库:
library(shiny)
library(RSQLite)
setwd("E:/shiny/Correct")
db <- dbConnect(SQLite(), dbname="db.sqlite")
dbSendQuery(conn = db,"CREATE TABLE users (username TEXT, password TEXT, email TEXT)")
dbSendQuery(db, "INSERT INTO users ( username, password, email) VALUES ( 'ester', 'silva', 'abc@gmail.com');")
答案 0 :(得分:1)
它无法正常工作,因为您无法在ui
个对象之间进行切换。您可以做的是在uiOutput
内创建ui
,并在运行时在不同的用户界面之间切换。
这是一个简单的例子。您可以添加自己的登录逻辑等等。
library(shiny)
ui <- fluidPage(
uiOutput("ui")
)
server <- function(input, output, session) {
USER <- reactiveValues(Logged = FALSE)
observe({
if (USER$Logged == FALSE) {
output$ui <- renderUI({
tagList(
h2("Hello", align = "center"),
div(
id = "login",
wellPanel(
textInput("userName", "Username"),
passwordInput("passwd", "Password"),
br(), actionButton("Login", "Log in")
)
)
)
})
} else if (USER$Logged == TRUE) {
output$ui <- renderUI({
tagList(
tabPanel(""),
pageWithSidebar(
headerPanel(
""
),
sidebarPanel(
actionButton("logout", "Logout")
),
mainPanel(tableOutput("aaa"))
)
)
})
}
})
observeEvent(input$Login, {
USER$Logged <- TRUE
})
observeEvent(input$logout, {
USER$Logged <- FALSE
})
}
shinyApp(ui, server)