首页 > 解决方案 > 在功能组件中反应 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

标签: javascriptreactjsreact-adminuse-state

解决方案


console.log('Index after updating: ',currentRowIndex);这给出了 0,因为没有确认当浏览器执行此状态时已经更新。

当您在更新完成后看到索引值时,您只需在 useEffects 中打印索引,其中包含依赖项列表,[currentRowIndex]然后它表明您的索引正在正确更新。

如果您可以提供信息,您究竟想用这个更新的值做什么,那么它将帮助我们更好地了解问题。


推荐阅读