我正在检查组件是否已卸载,以避免调用状态更新函数。
- 这是第一个选项,并且有效
const ref = useRef(false)
useEffect(() => {
ref.current = true
return () => {
ref.current = false
}
}, [])
....
if (ref.current) {
setAnswers(answers)
setIsLoading(false)
}
....
- 第二个选项是使用 useState,它的
isMounted
始终为 false,尽管我在组件 did mount 中将其更改为true
const [isMounted, setIsMounted] = useState(false)
useEffect(() => {
setIsMounted(true)
return () => {
setIsMounted(false)
}
}, [])
....
if (isMounted) {
setAnswers(answers)
setIsLoading(false)
}
....
与第一个选项相比,为什么第二个选项不起作用?
最佳答案
我编写了这个自定义钩子(Hook),它可以检查组件当前是否已安装,如果您有一个长时间运行的操作并且组件可能在完成并更新 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 (...)
}
现场演示
关于reactjs - 使用 react 钩子(Hook)检查组件是否已卸载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58979309/