Hooks方式
RestoredScroll.js
import { useEffect } from 'react'
import qs from 'qs'
import { debounce } from 'lodash-es'
import { getScrollTop } from '@@/utils/dom'
import { getSessionStorageCache } from '@@/utils/storage'
const RestoredScroll = ({ location, children }) => {
const { pathname, query } = location
const cacheKey = `${pathname}${qs.stringify(query)}`
const cache = getSessionStorageCache(cacheKey)
const storeScrollTop = debounce(() => {
const scrollTop = getScrollTop()
cache.set({ scrollTop })
}, 500, { leading: false, trailing: true })
useEffect(() => {
const scrollCache = cache.get()
const { scrollTop = 0 } = Object.assign({}, scrollCache)
setTimeout(() => {
window.scrollTo(0, scrollTop)
}, 0)
window.addEventListener('scroll', storeScrollTop)
return () => {
window.removeEventListener('scroll', storeScrollTop)
}
}, [cacheKey])
return children
}
export default RestoredScroll
配置路由
const routes = [
{
path: '/',
component: '../layouts/RestoredScroll', // 这个是 上面的RestoredScroll.js
Routes: ['src/layouts/LoginRequired'],
routes: [
// 课程资源
{
path: '/resource',
routes: [
{
path: '/resource/:uniqueId',
component: './Resource/DetailPage',
Routes: ['src/layouts/ShareWrapper']
}
]
}
]
}
]