Hooks方式

RestoredScroll.js

  1. import { useEffect } from 'react'
  2. import qs from 'qs'
  3. import { debounce } from 'lodash-es'
  4. import { getScrollTop } from '@@/utils/dom'
  5. import { getSessionStorageCache } from '@@/utils/storage'
  6. const RestoredScroll = ({ location, children }) => {
  7. const { pathname, query } = location
  8. const cacheKey = `${pathname}${qs.stringify(query)}`
  9. const cache = getSessionStorageCache(cacheKey)
  10. const storeScrollTop = debounce(() => {
  11. const scrollTop = getScrollTop()
  12. cache.set({ scrollTop })
  13. }, 500, { leading: false, trailing: true })
  14. useEffect(() => {
  15. const scrollCache = cache.get()
  16. const { scrollTop = 0 } = Object.assign({}, scrollCache)
  17. setTimeout(() => {
  18. window.scrollTo(0, scrollTop)
  19. }, 0)
  20. window.addEventListener('scroll', storeScrollTop)
  21. return () => {
  22. window.removeEventListener('scroll', storeScrollTop)
  23. }
  24. }, [cacheKey])
  25. return children
  26. }
  27. export default RestoredScroll

配置路由

  1. const routes = [
  2. {
  3. path: '/',
  4. component: '../layouts/RestoredScroll', // 这个是 上面的RestoredScroll.js
  5. Routes: ['src/layouts/LoginRequired'],
  6. routes: [
  7. // 课程资源
  8. {
  9. path: '/resource',
  10. routes: [
  11. {
  12. path: '/resource/:uniqueId',
  13. component: './Resource/DetailPage',
  14. Routes: ['src/layouts/ShareWrapper']
  15. }
  16. ]
  17. }
  18. ]
  19. }
  20. ]