javascript
export function getSession(key) {
return sessionStorage.getItem(key)
}
export function setSession(key, value) {
sessionStorage.setItem(key, value)
}
export function clearSession(key) {
sessionStorage.removeItem(key)
}
export function getRouteParamSession(key) {
const data = JSON.parse(sessionStorage.getItem('ROUTE-PARAMS') || '{}')
return data[key]
}
export function setRouteParamSession(key, value) {
const data = JSON.parse(sessionStorage.getItem('ROUTE-PARAMS') || '{}')
data[key] = value
sessionStorage.setItem('ROUTE-PARAMS', JSON.stringify(data))
}
export function clearRouteParamSession(key) {
if (key === 'all') {
sessionStorage.removeItem('ROUTE-PARAMS')
} else if (key) { // 如果 key 不是 'all',只删除一个属性而不是整个对象
const data = JSON.parse(sessionStorage.getItem('ROUTE-PARAMS') || '{}')
if (data[key]) {
delete data[key]
sessionStorage.setItem('ROUTE-PARAMS', JSON.stringify(data))
}
}
}
javascript
// 暂存当前页面的请求参数,达到在返回页面保持状态
const saveParams = (params)=>{
setRouteParamSession('data1', params)
}
const getParams = ()=>{
return getRouteParamSession('data1')
}
刷新页面清空数据
javascript
// 页面刷新(hooks)
useEffect(()=>{
const handleBeforeUnload = () => {
clearRouteParamSession('data1')
}
window.addEventListener('beforeunload', handleBeforeUnload)
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload)
if (React.$share) {
React.$share.destroy()
}
}
},[])
javascript
//(类组件,生命周期)
handleBeforeUnload = () =>{
clearRouteParamSession('data1')
}
componentDidMount() {
window.addEventListener('beforeunload', this.handleBeforeUnload)
}
componentWillUnmount(){
window.removeEventListener('beforeunload', this.handleBeforeUnload)
}