gpt4 book ai didi

reactjs - useEffect 惰性创建的清理函数

转载 作者:行者123 更新时间:2023-12-03 14:24:57 25 4
gpt4 key购买 nike

我正在尝试创建一个使用副作用的钩子(Hook),其中副作用函数返回清理回调。但是我只想在组件卸载时调用它,而不是在重新渲染时调用它。

使用空 deps 数组调用 useEffect 时的正常方法在这里不起作用,因为清理函数仅在第一次调用 Hook 时创建一次。但我的清理是后来创建的,所以没有办法改变它。


function useListener(data) {
const [response, updateResponse] = useState(null);

useEffect(
() => {
if (data) {
const removeListener = callRequest(data, resp => {
updateResponse(resp);
});

return removeListener;
}
},
[data]
);

return response;
}

这归结为以下问题:在普通的类组件中,willComponentUnmount 可以根据当前组件状态做出决定,但在 useEffect 的情况下,状态通过闭包传递给清理并如果状态发生变化,以后就无法传递信息了

最佳答案

您可以使用useRef保存和更新您的回调函数

The useRef() Hook isn’t just for DOM refs. The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class. more

function useListener(data) {
const [response, updateResponse] = useState(null);
const cleanUpCallbackRef = useRef(() => {});

useEffect(
() => {
if (data) {
cleanUpCallbackRef.current = callRequest(data, resp => {
updateResponse(resp);
});
}
},
[data]
);

useEffect(() => {
return () => {
cleanUpCallbackRef.current();
}
}, []);
return response;
}

我创建了一个简单的示例 here

关于reactjs - useEffect 惰性创建的清理函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56125679/

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