【问题标题】:Why do I have to click Submit button TWICE in order to update my useState() hook?为什么我必须单击提交按钮 TWICE 才能更新我的 useState() 挂钩?
【发布时间】:2022-01-11 09:08:51
【问题描述】:

我正在尝试创建一个函数,当它被重定向到另一个页面时 经过身份验证,但是,当我单击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

【问题讨论】:

    标签: javascript reactjs authentication passport.js


    【解决方案1】:

    我认为这是因为,即使您调用了 set state,它也可能尚未完成。这是因为 react 批量执行设置状态调用。为什么不使用使用效果来监视状态变量并在找到正确的值时重定向。

    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
    

    【讨论】:

      猜你喜欢
      • 2015-07-02
      • 1970-01-01
      • 2021-12-30
      • 2021-01-29
      • 2014-02-15
      • 2015-10-27
      • 1970-01-01
      • 2013-01-10
      • 1970-01-01
      相关资源
      最近更新 更多