Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

useEffect离开页面记录当前数据的问题

举个例子

const [count, setCount] = useState(0)

// 页面中会改count值

离开页面的时候希望保存当前的count值到localStorage

// 方式一
useEffect(()=>{
    return function(){
        localStorage.set('count', count) 
    }
},[])

方式一的问题是count一直是0。。。。

// 方式二
useEffect(()=>{
    return function(){
        localStorage.set('count', count)
    }
},[count])

方式二的问题是每次更改count,都会执行

希望可以只是页面卸载时才执行的函数,类似生命周期函数componentWillUnmount。应该怎么写?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

还有一种情况啊,文档详细写了的。第一个参数的函数有返回值(函数)的时候,该函数会在组件清除的时候执行。一般资源的保存或者释放都是这一步。参见说明

image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...