React state hook Object未更新,正在获取[Object-Object]



在我的项目中,我在用javascript对象设置状态变量时遇到了问题,我可以在控制台日志中看到该对象正在使用正确的值正确安装,但我不明白为什么它没有正确设置状态挂钩。

任何帮助都将不胜感激!!

const [accountInfo, setAccountInfo] = useState({})
const delay = ms => new Promise(res => setTimeout(res, ms));
const onLogin = async (account) => {
await(delay(2000));
console.log(account); // I am getting the proper output of the object here
if(account.account_id != -1){
setAccountInfo(account);
await delay(4000); //Just for debugging
console.log("acc " + accountInfo); // This outputs [Object object]
setLoggedIn(true);
}else{
alert('Account does not exist');
}
}

您正在尝试将字符串与对象连接起来。使用JSON.stringify将对象转换为字符串,或者使用object.properties.

console.log("Object" + JSON.stringify(object_to_print));

您正在尝试console.log一个状态变量。React并不能保证状态立即改变。您可以在useEffect挂钩中访问状态更改

useEffect(() => { 
console.log('state changed', your-state-variable) 
// write your callback function here
}, [your-state-variable]);

最新更新