React hook 新手...
给定这个例子
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
// Specify how to clean up after this effect:
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
来自文档
React performs the cleanup when the component unmounts. However, as we learned earlier, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time.
这是否意味着 unsubscribeFromFriendStatus
仅在组件卸载或每次渲染时运行一次?
扩展我的问题:
如果unsubscribeFromFriendStatus
每次都会运行,跳过它的唯一方法是使用可选的第二个参数...那么它不会更难实现 componentWillMount
的原始显式执行吗?和 componentWillUnmount
?说,我要 subscribe
什么时候componentWillMount
, 并且只运行 unsubscribe
什么时候componentWillUnMount
?
最佳答案
Does that mean
unsubscribeFromFriendStatus
only gets run when once when component unmounts or every render?
unsubscribeFromFriendStatus
运行每次重新渲染。
每次重新渲染,即使 props.friend.id
从未改变,它也会取消订阅并重新订阅。
要改善这一点,请仅在 props.friend.id
更改时运行效果。
这可以通过将其添加为 useEffect()
的依赖项来实现。
useEffect(
() => { /* subscription */ }
, [props.friend.id] // add as dependency
)
doesn't it make it harder to implement the original explicit execution of componentWillMount and componentWillUnmount? Say, I want to subscribe when componentWillMount, and only run unsubscribe when componentWillUnMount?
使用 props.friend.id
的旧值维护旧订阅没有意义。
订阅使用资源(websocket 或观察者)。在 componentWillUnmount
期间取消订阅时,只会取消订阅 props.friend.id
的最新值。
旧订阅会怎样?没有被释放。 因此,您有一个内存泄漏。
关于javascript - React useEffect 清理函数运行多次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58424470/