是否使用Reaction挂钩检查组件是否已卸载? [英] Checking if a component is unmounted using react hooks?

查看:36
本文介绍了是否使用Reaction挂钩检查组件是否已卸载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在检查组件是否已卸载,以避免调用状态更新函数。

  1. 这是第一个选项,它起作用
const ref = useRef(false)
  useEffect(() => {
    ref.current = true
    return () => {
      ref.current = false
    }
  }, [])

....
if (ref.current) {
  setAnswers(answers)
  setIsLoading(false)
}
....
  1. 第二个选项是使用useState,它isMounted始终为false,尽管我在Component Do mount
  2. 中将其更改为true
const [isMounted, setIsMounted] = useState(false)

useEffect(() => {
  setIsMounted(true)
  return () => {
    setIsMounted(false)
  }
}, [])

....
if (isMounted) {
  setAnswers(answers)
  setIsLoading(false)
}
....

与第一个选项相比,为什么第二个选项不起作用?

推荐答案

我编写了此自定义挂钩,它可以检查组件当前是否已装入,如果您有一个长时间运行的操作,并且组件可能会在完成并更新UI状态之前卸载,这一点很有用。

import { useCallback, useEffect, useRef } from "react";

export function useIsMounted() {
  const isMountedRef = useRef(true);
  const isMounted = useCallback(() => isMountedRef.current, []);

  useEffect(() => {
    return () => void (isMountedRef.current = false);
  }, []);

  return isMounted;
}

用法

function MyComponent() {
  const [data, setData] = React.useState()
  const isMounted = useIsMounted()

  React.useEffect(() => {
    fetch().then((data) => {
      // at this point the component may already have been removed from the tree
      // so we need to check first before updating the component state
      if (isMounted()) {
        setData(data)
      }
    })
  }, [...])

  return (...)
}

实时演示

这篇关于是否使用Reaction挂钩检查组件是否已卸载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆