UseState 仅在第二次点击时显示

UseState only shows on second click

我在单击表单提交按钮时使用 React useState 钩子更新状态,直到第二次单击时状态才会更新。相信我需要使用 useEffect 但不确定如何使用 onClick 来实现。

const files = [
  {
    id: 'foo'
  }
]

const [fieldName, setName] = useState({});


const onSubmit = () => {
    files.map((file) => {
      if (!fieldName[file.id]?.value) {
        setName(() => ({
          ...fieldName,
          [file.id]: {
            value: test[file.id]?.value,
            error: true
          },
        }));
      }
    });

    console.log(fieldName);
    // Output = {}
    // Expected Output = { foo: { error: true } }
    
    if (fieldName) // simply to show i need access to updated fieldName at this point

  };

如评论中所述; useState 是一个异步函数,因此不能保证您会在再次检索其值时获得新值。这是出于性能原因,允许批处理多个状态更改。

在同一方法中继续使用新值的最简单方法是将其保存到变量中,如下所示:

const [clicked, setClicked] = useState(false);

function onclick(e) {
  setClicked(true);
  if (clicked) { //this goes wrong as clicked likely isn't updated yet
    //do something
  }
}
const [clicked, setClicked] = useState(false);

function onclick(e) {
  const newClicked = true;
  setClicked(newClicked);
  if (newClicked) { //using the variable garantuees you'll get the value you want
    //do something
  }
}

我实现了一个 useEffect 来设置 hasError 状态

useEffect(() => {
    const hasErrors = Object.keys(fieldName).filter(
      (key) => fieldName[key].error
    );
    if (!hasErrors.length) {
      setFormHasError(() => true);
    }
  }, [fieldName]);

然后我可以在代码中使用以下内容

if (formHasError) {
      return;
    }