1.监听路由变化

const location = useLocation()
  useEffect(() => {
    // 路由变化时执行的代码
    console.log('路由变化:', location.pathname)
    handleSavePreviousRoute(location.pathname + location.search)
  }, [location])

2.处理路由缓存

  const handleSavePreviousRoute = (url) => {
    let currentRoute = localStorage.getItem('previousRoute')?JSON.parse(localStorage.getItem('previousRoute')) : ['', '']
    // 获取当前路由的index
    if(url.indexOf("/login) == -1 && currentRoute[0] != url){
      currentRoute.unshift(url)
      localStorage.setItem("previousRoute",JSON.stringify(currentRoute.slice(0,2)))

    }
  }

防止数据类型出错采用默认的Array(2),unshift当前最新的路由始终在0位

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐