reactjs - 我如何“等待” setState 更新或具有相同效果的东西?
问题描述
我有一个事件处理函数,它更新一些状态,然后基于相同的状态创建一个条件。当然,条件并不反映更新的状态。有没有办法等待状态的变化?如果没有,我该如何实现?
async function handleClick(event) {
console.log(values)
// make sure email is not empty
if (values.email.length === 0) {
setErrors({...errors, email: [{msg: "Email can not be empty."}]});
}
// make sure password is not empty
if (values.password.length === 0) {
setErrors((prev) => ({...prev, password: [{msg: "Password can not be empty."}]}));
};
console.log('about to submit: ', errors);
if (errors.email || errors.password) return;
console.log('data is clean');
}
解决方案
React 状态更新是异步处理的,但是useState
状态更新函数是完全同步的,并且不返回 Promise,所以不能等待。
您可以在处理程序中收集错误并发出单个状态更新。
function handleClick(event) {
console.log(values);
const errors = {};
// make sure email is not empty
if (values.email.length === 0) {
errors.email = [{msg: "Email can not be empty."}];
}
// make sure password is not empty
if (!values.password.length) {
errors.password = [{msg: "Password can not be empty."}];
};
console.log('about to submit: ', errors);
if (Object.keys(errors).length) { // if there are errors
setErrors(errors);
return;
}
console.log('data is clean');
}
推荐阅读
- php - PHP:使用管道输入密码运行 shell 命令
- php - “img”标签如何显示正在运行的视频(很想知道)
- c++ - 如何利用 fstream 从 .txt 文件 C++ 中取出 int 值
- math - 如何解决两个圆相交点垂直的问题?
- c++ - 如何返回使用参数包定义的成员函数的 std::function 对象?
- django - Django CMS 如何写博客
- android - 如何在 Unity 中使用 Google 帐户对用户进行身份验证?
- xaml - TabView 的子项中触发了哪些事件?
- angular - 您如何为 Angular 8 中的 HTML5 画布动态设置 clientHeight 和 clientWidth?
- modelica - 搜索 Modelica.Userguide