[英]Why do I have to click Submit button TWICE in order to update my useState() hook?
我正在尝试创建一个 function 在通过身份验证时重定向到不同的页面,但是,当我单击onSubmit
按钮时, authenticate
不会立即更新。 我必须单击提交两次才能将authenticate
从null
更改为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 批量执行 set state 调用。 为什么不使用使用效果来监视 state 变量并在找到正确值时重定向。
const newUser = (event) =>{
event.preventDefault()
axios({
method: "POST",
url: 'xxxxxxxxxxxxxxxxx',
data:{
username,
password
}
}).then(res=>setAuthenticate(res.data));
然后创建一个使用效果监控state变量
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.