NextJS 未在按钮单击时设置状态
NextJS not setting state on button click
我的 NextJS 应用程序有问题。我试图在按钮尝试登录用户时向按钮显示 class(加载微调器)。我通过在调用登录函数之前将 loading
状态设置为 true 来实现此目的,并且然后在完成后将状态设置为 false(在 submitForm
函数中),但它似乎没有设置它。每当我单击按钮时,状态都会停留在 false
。任何帮助将不胜感激。
import { useAuth } from '@/hooks/auth'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import ButtonSpinner from '@/styles/buttonspinner.module.css'
export default function Home() {
const router = useRouter()
const { login } = useAuth({
middleware: 'guest',
redirectIfAuthenticated: '/dashboard',
})
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [errors, setErrors] = useState([])
const [status, setStatus] = useState(null)
const [loading, setLoading] = useState(false)
useEffect(() => {
if (router.query.reset?.length > 0 && errors.length === 0) {
setStatus(atob(router.query.reset))
} else {
setStatus(null)
}
})
const submitForm = async event => {
event.preventDefault()
setLoading(true)
login({ email, password, setErrors, setStatus })
setLoading(false)
}
return (
<div>
<form className="mt-8 space-y-6" onSubmit={submitForm} autoComplete="off">
<button className={"shadow-sm relative w-full " + (loading ? ButtonSpinner['btn-loading'] : "")}>
Sign in
</button>
</form>
</div>
)
}
您没有在等待登录响应
const submitForm = async event => {
event.preventDefault()
setLoading(true)
try {
await login({ email, password, setErrors, setStatus });
} finally {
setLoading(false)
}
}
我的 NextJS 应用程序有问题。我试图在按钮尝试登录用户时向按钮显示 class(加载微调器)。我通过在调用登录函数之前将 loading
状态设置为 true 来实现此目的,并且然后在完成后将状态设置为 false(在 submitForm
函数中),但它似乎没有设置它。每当我单击按钮时,状态都会停留在 false
。任何帮助将不胜感激。
import { useAuth } from '@/hooks/auth'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import ButtonSpinner from '@/styles/buttonspinner.module.css'
export default function Home() {
const router = useRouter()
const { login } = useAuth({
middleware: 'guest',
redirectIfAuthenticated: '/dashboard',
})
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [errors, setErrors] = useState([])
const [status, setStatus] = useState(null)
const [loading, setLoading] = useState(false)
useEffect(() => {
if (router.query.reset?.length > 0 && errors.length === 0) {
setStatus(atob(router.query.reset))
} else {
setStatus(null)
}
})
const submitForm = async event => {
event.preventDefault()
setLoading(true)
login({ email, password, setErrors, setStatus })
setLoading(false)
}
return (
<div>
<form className="mt-8 space-y-6" onSubmit={submitForm} autoComplete="off">
<button className={"shadow-sm relative w-full " + (loading ? ButtonSpinner['btn-loading'] : "")}>
Sign in
</button>
</form>
</div>
)
}
您没有在等待登录响应
const submitForm = async event => {
event.preventDefault()
setLoading(true)
try {
await login({ email, password, setErrors, setStatus });
} finally {
setLoading(false)
}
}