如何解决在功能组件中反应 useState 不会立即更新属性值
react useState 钩子不会更新属性值并显示旧值,甚至在一段时间后访问它。我知道它是异步更新,但最终它应该更新值。 这是我的代码:
const [ currentRowIndex,setCurrentRowIndex] = useState(0);
React.useEffect(() => {
console.log('Index from useEffect: ',currentRowIndex);
setCurrentRowIndex(currentRowIndex);},[currentRowIndex]);
..
..
..
const handleClick = (event,index) => {
console.log('Index after click: ',index);
setCurrentRowIndex(index);
setTimeout(function(){
console.log('Index in timeout: ',currentRowIndex);
},3000);
console.log('Index after updating: ',currentRowIndex);
};
控制台输出:
Index after click: 4
Index after updating: 0
Index from useEffect: 4
Index in timeout: 0
解决方法
console.log('Index after updating: ',currentRowIndex);
这是给 0,因为它没有确认浏览器执行此状态时是否已经更新。
当您希望在更新完成后查看索引值时,您只需在 useEffects 中打印索引,其中包含 [currentRowIndex]
的依赖项列表,然后它就会显示您的索引正在正确更新。
如果您能提供信息,您究竟想用这个更新后的值做什么,那么这将有助于我们更好地了解问题。
,一切都按预期发生,考虑每次将组件渲染为框架。
当您调用 handleClick 时,currentRowIndex 为 0,您将 0 传递给 setTimeout 并打印 0,因为该函数在此特定渲染中将 currentRowIndex 记住为 0,当状态更新时该函数不会更改。>
如果在 Text 组件中渲染 currentRowIndex,您将看到它确实更新了,因为新渲染具有更新的状态。
您可以在 handleClick 之外打印它并查看每个渲染上的状态值。
console.log('Index: ',currentRowIndex);
const handleClick = (event,index) => {
...
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。