我尝试用提取的数据更新useState中的值。当我console.logdata.success时,它返回true//strong>。然后我将其分配给success值。但它返回false!为什么?为什么价值成功没有立即更新。最后,我从服务器收到登录成功的消息。登录成功:false用户管理员已记录
const Signin = () => {
const [values, setValues] = useState({
success: false
});
const { success } = values;
const clickSubmit = async event => {
event.preventDefault();
const signReact = catchAsync(async (email, password) => {
const data = await signin(email, password) // fetch data from the server
console.log(data.success); // -> true
if (data) {
setValues({
...values, success: data.success // -> assign to success
});
console.log("SIGN IN success: " + success); // -> false! why?!
}
return data;
});
signReact(email, password);
};
使用useEffect。试试这样的东西:
useEffect(() => {
console.log("SIGN IN success: " + values.success);
}, [values]);
...
...
const data = await signin(email, password);
setValues(prevState =>{...prevState, success: data.success});
setState()
是一个异步函数。因此,您不能在下一个语句中打印它。这需要一些时间。要查看更新后的状态值,您可以像下面的一样将其记录在useEffect()
中
useEffect(()=>{
console.log(values);
},[values])
根据文档:
对setState的调用是异步的-不要依赖this.state来在调用setState后立即反映新值。如果需要根据当前状态计算值,请传递更新程序函数而不是对象:
示例:
const Signin = () => {
const [values, setValues] = useState({
success: false
});
const { success } = values;
React.useEffect(()=> {
console.log("SIGN IN success: " + success);
}, [values]);
const clickSubmit = async event => {
event.preventDefault();
const signReact = catchAsync(async (email, password) => {
const data = await signin(email, password) // fetch data from the server
console.log(data.success); // -> true
if (data) {
setValues({
...values, success: data.success // -> assign to success
});
}
return data;
});
signReact(email, password);
};