gpt4 book ai didi

javascript - react : State is not up-to-date when I unmount component

转载 作者:行者123 更新时间:2023-12-04 14:47:48 25 4
gpt4 key购买 nike

在我的工作中,当有人离开页面时,我必须发出一个 http 请求。我的想法是在该页面的组件卸载时执行此请求。

如果我理解正确的话,这可以通过将逻辑放在 useEffect 的返回函数中来完成。当我这样做时,它会在正确的时间触发,但我想使用的状态值不是最新的。有没有办法获取最新值?

      useEffect(() => {

return () => {

//this runs on unmount
// but the state changes that happened are not registered it seems
}
}, [])

我在 codesandbox 中创建了一个简单示例:当您将状态从 4 更改为 8 然后隐藏组件时。卸载中的 NUM 值仍然是 4(检查控制台日志)。卸载组件时如何获取当前状态值?

https://codesandbox.io/live/b6e65d13114

https://codesandbox.io/s/loving-galois-okb0b (不确定分享哪个链接最好)

最佳答案

您可以使用 React ref 来缓存状态副本以在清理函数中访问。

import { useEffect, useRef, useState } from "react";

export const NumCheck = () => {
const [num, setNum] = useState(4);
const stateRef = useRef(); // <-- ref to cache state value

useEffect(() => {
stateRef.current = num; // <-- cache state value on change
}, [num]);

useEffect(() => {
return () => {
console.log("NUM CHECK", stateRef.current); // <-- access cached state value
};
}, []);

return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>click the button to change number</h2>
<button onClick={() => setNum(8)}>click me</button>

<br />
<br />
<h5>{num}</h5>
</div>
);
};

Edit react-state-is-not-up-to-date-when-i-unmount-component

关于javascript - react : State is not up-to-date when I unmount component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69694204/

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