使用useEffect向服务器异步请求的时候,切换组件弹出错误
Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
1、检查定时器是否销毁
useEffect(() => {
let imgArray = [img1, img2, img3, img4, img5, img9]
let dom: any = document.querySelector(`.${style.move}`)
let timeout = setTimeout(() => {
let Div = document.createElement("div")
let Img = document.createElement('img')
Img.setAttribute('class', `${style.slideshow}`)
Img.setAttribute('src', `${imgArray[imgIndex]}`)
Div.setAttribute('class', `${style.box2}`)
Div.appendChild(Img)
dom.appendChild(Div)
timer(dom)
}, 5000)
return () => clearTimeout(timeout)//销毁定时器
}, [imgIndex])
2、取消异步请求
useEffect(() => {
let isMounted = false
appApi.listNotification().then((r: any) => {
if (!isMounted) {
setListData(r.result)
}
})
return () => {
isMounted = true //自定义条件,当前组件是否销毁
}
}, [setListData])