reactjs - 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
};
解决方案
如评论中所述;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
}
}
推荐阅读
- php - 在工厂模式php中处理动态类名
- html - Angular:尝试禁用按钮时出现 ExpressionChangedAfterItHasBeenCheckedError
- javascript - 如何在不将其附加到 DOM 的情况下使用 javascript
- r - r - 通过自举/重采样生成负二项分布
- php - 当我在 div 标签中回显会话变量(包含图像路径)时,它没有显示所有图像
- networking - Juniper SRX 210 vlan 接口配置
- powerbi - 将 DAX 度量保存到表中(ABC /帕累托分析)
- python - OSError:使用 ytree 的文件不存在
- laravel - 如何通过一个 foreach 循环完成三个 foreach 循环的工作?
- java - 如何点击 SearchView 中的建议?