gpt4 book ai didi

javascript - React Hooks State 第一次没有更新

转载 作者:行者123 更新时间:2023-12-02 02:30:18 24 4
gpt4 key购买 nike

设置状态和更新状态的函数:

const [objectivesOpen, setObjectivesOpen] = useState([]);
const toggleObjectives = () => {
console.log('objectivesOpenNotUpdated', objectivesOpen);
setObjectivesOpen([Math.random()]);
}

调用函数:

<button onClick={toggleObjectives}>Test</button>

objectivesOpen 下次单击按钮后未获取更新的值。

更新:该值在 useEffect() 中更新,但在单击按钮时不会更新。

useEffect(() => {
console.log('objectivesOpen in effect', objectivesOpen);
});

const toggleObjectives = () => {
console.log('time:', new Date())
console.log('objectivesOpen', objectivesOpen);

setObjectivesOpen([Math.random()]);
};

结果:

time: Thu Dec 03 2020 17:17:58 GMT+0100 (Central European Standard Time)
objectivesOpen [0.4735904311779686]
objectivesOpen in effect [0.12100479433701583]
time: Thu Dec 03 2020 17:18:01 GMT+0100 (Central European Standard Time)
objectivesOpen [0.4735904311779686]
objectivesOpen in effect [0.6376121961469396]

最佳答案

setObjectivesOpen 是异步方法,您无法在 setObjectivesOpen 之后立即获取更新的 objectivesOpen 值。

您应该使用 useEffect 并添加 objectivesOpen 依赖项来获取更新的 objectivesOpen 值。

useEffect(() => {
console.log('objectivesOpenNotUpdated', objectivesOpen);
}, [objectivesOpen]);

关于javascript - React Hooks State 第一次没有更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65129635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com