首页 > 解决方案 > 我如何“等待” 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');
}

标签: reactjsreact-hooksuse-state

解决方案


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');
}

推荐阅读