为什么我必须点击两次提交按钮才能更新我的useState()挂钩



我正在尝试创建一个函数,该函数在已验证,但是,当我单击onSubmit按钮时,authenticate不会立即更新。我必须点击两次提交才能将authenticatenull更改为false/true?为什么authenticate会立即更新,我该怎么办才能解决这个问题?谢谢

import React, {useEffect,useState} from 'react'
import Dashboard from './Dashboard'
import {useNavigate} from "react-router-dom"
import axios from 'axios'
function Register() {
const navigate = useNavigate()
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [authenticate, setAuthenticate] = useState(null)
const newUser = (event) =>{
event.preventDefault()
axios({
method: "POST",
url: 'xxxxxxxxxxxxxxxxx',
data:{
username,
password
}
}).then(res=>setAuthenticate(res.data))
.then(()=>console.log(authenticate))
.then(()=>authentication())
}
const authentication = () =>{
authenticate ? 
navigate("/dashboard")
: console.log('Cannot create User')
}

return (
<div>
<form onSubmit={newUser}>
<label>Username: </label>
<input 
type="text"
value={username}
onChange={e=> setUsername(e.target.value)}
/>
<br />
<label>Password: </label>
<input 
type="text"
value={password}
onChange={e=>setPassword(e.target.value)}
/>
<br />
<button>Submit</button>
</form>
<div>
{username}
</div>
</div>
)
}
export default Register

我认为发生这种情况是因为,即使您调用了set state,它也可能尚未完成。这是因为react批量执行集合状态调用。为什么不使用useeffect来监控状态变量,并在找到正确值时重定向呢。

const newUser = (event) =>{
event.preventDefault()
axios({
method: "POST",
url: 'xxxxxxxxxxxxxxxxx',
data:{
username,
password
}
}).then(res=>setAuthenticate(res.data));

然后创建一个使用效果来监控状态变量

useEffect(() => {
if (authenticate) { //this check is required as useEffect gets executed when the component is mounted. 
navigate("/dashboard");
}
},[authenticate]) //have put authenticate in the dependencies of the use effect since thats what you need to monitor

最新更新