[英]React function component state is not available at ComponentWillUnmount
我需要在 ComponentWillUnmount 時調用 api。 我使用 state 變量來設置 api 請求。 當我從 ComponentWillUnmount 訪問 state 變量時。 state 值是默認值,但我期待最近更新的 state。
export const sampleComponent: React.FC<IProps> = (props: IProps) => {
const [apiValue, setAipValue] = useState("");
const [updateRec] = useMutation(UPDATE_REC);
....
setApiValue
....
useEffect(()=>{
return () => {callApi(apiValue)}
}, []);
}
const callApi = (input) => {
updateRec({
variables : {
data : input
}
});
}
由於您的 useEffect 具有空依賴項( []
),因此綁定的 apiValue 只是 apiValue 的初始值
一個解決方案是使用 ref 來跟蹤價值
const apiValueRef = useRef();
apiValueRef.current = apiValue;
useEffect(() => {
return () => {
callApi(apiValueRef.current);
}
}, []);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.