gpt4 book ai didi

reactjs - React - useState 即使在对其进行操作后也会返回初始化值

转载 作者:行者123 更新时间:2023-12-04 03:31:40 25 4
gpt4 key购买 nike

这是我的代码:

import React,{useEffect, useState} from 'react';
import bootstrap from '../../node_modules/Bootstrap/dist/css/bootstrap.min.css'
import '../ComponentStyles/NavbarStyle.css'
function Navbar() {
const [LUsername,setLUsername]=useState('')
const [LPassword,setLPassword]=useState('')
const [IsLogin,setIsLogin]=useState(false)

function Login(){

let credentials = JSON.parse(localStorage.getItem('cred'))
console.log(credentials)
for(let i=0;i<credentials.length;i++) {

if(credentials[i].username===LUsername && credentials[i].password===LPassword){
alert('in')
// why does IsLogin value is false even after setting it to true
setIsLogin(false)
alert(IsLogin)
}

}
if(IsLogin){
alert('login')
}

else{
alert('Login Failed')
}

在第 7 行,我用 useState 初始化了 Isl​​ogin 变量。在第 18 行,我使用 setIsLogin 方法将其初始值从 false 更改为 true

但是当我使用 alert 输出它的值时,它会给我初始值,该值是 false。当我在第 45 行使用条件渲染时,返回的值也是 true,它在那里工作正常,有人能告诉我为什么值在警报中显示错误吗?谢谢。

最佳答案

返回一个有状态的值,以及一个更新它的函数。可以使用新值或更新函数参数调用更新状态的函数。

如您所见,调用 setState 后的状态在更新前具有值。

我们有一些选择。调用更新程序只是为了获取最新的值。

const [value, setValue] = useState(false);
setValue(true);
setValue((state) => {
console.log(state); // true

return state;
});

带有异步状态选择器的 setState 自定义钩子(Hook)。

const [value, setValue, getValue] = useSetState(false);
setValue(true);
console.log(await getValue()); // true

关于reactjs - React - useState 即使在对其进行操作后也会返回初始化值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66686977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com