gpt4 book ai didi

reactjs - 卸载 react 组件时是否可以调度函数? ( react 功能组件)

转载 作者:行者123 更新时间:2023-12-04 11:35:46 25 4
gpt4 key购买 nike

嗨,我正在制作一些调用 api 并将该值保存在状态中的函数,然后它应该在用户离开组件时调度。所以我尝试使用 react useEffect hooks 作为 componentWillUnmount 并使用参数作为状态值调度一些 Action 。
但问题是调度 Action 是有效的,但带有空字符串..我认为以某种方式删除了状态值,然后执行了调度函数。那么当用户离开组件时,我有什么方法可以调用带有状态值的函数吗?

const [userCheck,setUserCheck]=React.useState('')

useEffect(() => {

const fetChItem='this is the function which calling api '
setUserCheck(fetChItem);

}, []);

useEffect(() => {
return () => {
dispatch(saveFetchValue(userCheck));

};
}, []);



最佳答案

问题
由于 shell 如何与 useEffect 一起工作,这将不起作用。打回来。与以下

useEffect(() => {
return () => {
dispatch(saveFetchValue(userCheck));
};
}, []);
您已附上首字母 userCheck返回的清理函数中的状态值 ( "" )。
解决方案
使用 react 引用和第二个 useEffect Hook “缓存”最新状态。
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
};
}, []);
演示
Edit is-it-possible-to-dispatch-function-when-react-component-is-unmount-react-fun

关于reactjs - 卸载 react 组件时是否可以调度函数? ( react 功能组件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65098296/

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