[英]is it possible to dispatch function when react component is unmount ? (React functional componet)
嗨,我正在制作一些 function,它調用 api 並將該值保存在 state 中,然后當用戶離開該組件時它應該分派。 所以我嘗試使用 react useEffect 鈎子作為 componentWillUnmount 並分派一些參數為 state 值的動作。 但問題是調度操作有效,但字符串為空。我認為 state 值以某種方式被刪除,然后執行調度 function。那么當用戶離開組件時,有什么方法可以用 state 值調用 function 嗎?
const [userCheck,setUserCheck]=React.useState('')
useEffect(() => {
const fetChItem='this is the function which calling api '
setUserCheck(fetChItem);
}, []);
useEffect(() => {
return () => {
dispatch(saveFetchValue(userCheck));
};
}, []);
這將不起作用,因為附件如何與useEffect
回調一起工作。 隨着以下
useEffect(() => {
return () => {
dispatch(saveFetchValue(userCheck));
};
}, []);
您已將初始userCheck
state 值 ( ""
) 包含在返回的清理 function 中。
使用一個 React ref 和第二個useEffect
鈎子來“緩存”最新的 state。
const [userCheck, setUserCheck] = React.useState('');
const userCheckRef = React.useRef(userCheck); // ref to store state value
React.useEffect(() => {
userCheckRef.current = userCheck; // save userCheck state value to ref
}, [userCheck]);
...
useEffect(() => {
return () => {
dispatch(saveFetchValue(userCheckRef.current)); // pass current ref value
};
}, []);
演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.