简体   繁体   English

对 event.target.value 未正确更新的 useState 问题做出反应?

[英]React useState issue with event.target.value not updating correctly?

My issue is that my useState is getting wrong numbers我的问题是我的 useState 得到错误的数字

when I print e.target.value it for example outprints 1 but my selectedIndex gives me 2 or when I get 0 selectedIndex retrives 1 stuff like that.例如,当我打印 e.target.value 时,它会输出 1 但我的 selectedIndex 给了我 2 或者当我得到 0 selectedIndex 时会检索 1 类似的东西。 Any ideas why this could happen?任何想法为什么会发生这种情况?

<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>

When you console the state value imediately after setting will give you the older value.当您在设置后立即控制台 state 值会给您较旧的值。 Is that your issue?那是你的问题吗? Anyway the state will get updated.无论如何,state 将得到更新。 If you want to check the value change use as below after setting如果要检查值更改,请在设置后如下使用

React.useEffect(() => { console.log(selectedIndex)}, [selectedIndex]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM