Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k 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 Reply

0 votes
by (71.8m points)

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

image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...