需求
要把网页的某个状态保存起来,我考虑的是利用useEffect的清理函数将状态存在localStorage里面.
简单实现
const KEY = // ...
// ...
export class App(){
constructor(props) {
super(props)
this.state=this.getStateFromStorage()
}
componentWillUnmount(){
this.storeState()
}
}
不足
测试的时候发现,这段代码无法应对直接关闭网页或浏览器的情况。查阅资料后发现,componentWillUnmount只能由react卸载组件时调用,而网页的关闭要快于这一动作,应当监听beforeunload事件.useEffect清理函数类似,关闭网页后react没有机会执行清理函数
最终结果
在componentDidMount中监听事件
componentDidMount(){
window.addEventListener('beforeunload', ()=>this.storeState())
}