event.target.value 未正确更新的 React useState 问题?
React useState issue with event.target.value not updating correctly?
我的问题是我的 useState 得到了错误的数字
当我打印 e.target.value 时,它打印出 1,但我的 selectedIndex 给了我 2
或者当我得到 0 个 selectedIndex 时,会检索 1 个类似的东西。知道为什么会发生这种情况吗?
<Select
id="SelectGrade"
value={selectedIndex}
//Important part
onChange={(e) => {
console.log(e.target.value);
setSelectedIndex(e.target.value),
console.log(selectedIndex);
}}
>
{pflegeengel.map(({ Vorname }, index) => {
return (
<MenuItem value={index} key={index}>
{Vorname}
</MenuItem>
);
})}
</Select>
当您在设置后立即控制状态值时,将为您提供旧值。那是你的问题吗?无论如何,状态将得到更新。如果要检查值更改,请在设置
后按如下方式使用
React.useEffect(() => { console.log(selectedIndex)}, [selectedIndex]);
我的问题是我的 useState 得到了错误的数字
当我打印 e.target.value 时,它打印出 1,但我的 selectedIndex 给了我 2 或者当我得到 0 个 selectedIndex 时,会检索 1 个类似的东西。知道为什么会发生这种情况吗?
<Select
id="SelectGrade"
value={selectedIndex}
//Important part
onChange={(e) => {
console.log(e.target.value);
setSelectedIndex(e.target.value),
console.log(selectedIndex);
}}
>
{pflegeengel.map(({ Vorname }, index) => {
return (
<MenuItem value={index} key={index}>
{Vorname}
</MenuItem>
);
})}
</Select>
当您在设置后立即控制状态值时,将为您提供旧值。那是你的问题吗?无论如何,状态将得到更新。如果要检查值更改,请在设置
后按如下方式使用React.useEffect(() => { console.log(selectedIndex)}, [selectedIndex]);