首页 > 解决方案 > UseState 仅在第二次单击时显示

问题描述

我在单击表单提交按钮时使用 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

  };

标签: reactjsuse-effectuse-state

解决方案


如评论中所述;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
  }
}

推荐阅读