javascript - 在功能组件中反应 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]
然后它表明您的索引正在正确更新。
如果您可以提供信息,您究竟想用这个更新的值做什么,那么它将帮助我们更好地了解问题。
推荐阅读
- r - 更新 R 中数据框中的特定变量
- flutter - 如何在 Flutter 中创建自定义下拉框
- python - sqlalchemy OverflowError:太大而无法使用 dataframe.to_sql 进行转换
- java - Hibernate JPA - Wildfly 启动时未检测到实体
- javascript - 反应测试类型错误:无法读取未定义的属性“地图”
- reactjs - 在 React 中将 index 设置为 key 应该会破坏 UI,但它不会
- javascript - npm 错误:cb() 从未调用,我该怎么办?
- deep-learning - 修剪模型后删除 Pytorch 中的 weight_orig
- arrays - 如何从 .dat 文件中打印所有列元素以获取大量数据(~10,000)
- protractor - Shift + 量角器