就比如说下面这个请求时间太长了,在它还没有请求成功就切换了页面,销毁了页面组件,useEffect就会给它设置成true,抛弃这个请求。
const ignore = useRef(false)
useEffect(() => {
return () => {
ignore.current = true
}
}, [])
const getDetail = async () => {
try {
setLoading(true)
const res = await fetchLineDetail(lineId)
if (ignore.current || !res) return
const {state, data, msg} = res
if (state != 1) throw new Error(msg)
setLine(data)
setLoading(false)
} catch (e) {
if (e instanceof Error) {
message.error(e.message)
}
}
}