react获取访问过的路由历史记录

看了下,好像没有很好的解决方案,之前的useHistory现在也用不了了,

chatgpt说使用useMatch,也报错

看了下浏览器原生的。本来浏览器就会限制这个histroy的读取,只能获取length

https://developer.mozilla.org/zh-CN/docs/Web/API/Window/history

那考虑useEffect每次在location.pathname 进行变化的时候,直接进行存取队列。~~ 自己手动做吧。

const RouterComponent = (router: any) => {
  const location = useLocation()
  // 每一次路由变化的时候,去更新

  useEffect(() => {
    store.dispatch(setLastRouter(location.pathname))
  }, [location.pathname])

  return (
    <>
      <Routes>
        {routers.map((router) => (
          <Route
            path={router.path}
            element={
              router.authentication ? (
                <Authentication>{router.element}</Authentication>
              ) : (
                router.element
              )
            }
            key={router.path}
          ></Route>
        ))}
      </Routes>
    </>
  )
}

然后

import { PayloadAction, createSlice } from "@reduxjs/toolkit"
import { RootState } from "./store"

interface taskState {
  router: { lastRouter: null; currentRouter: null }
}
const initialState: taskState = {
  router: { lastRouter: null, currentRouter: null },
}

export const taskSlice = createSlice({
  name: "task1111",
  initialState,
  reducers: {
    setLastRouter: (state, action: PayloadAction<any>) => {
      state.router.lastRouter= state.router.currentRouter
      state.router.currentRouter = action.payload
    }
    
  },
})

export const { setLastRouter } = taskSlice.actions
export const selectLastRouter = (state: RootState) => state.task.router.lastRouter
export default taskSlice.reducer

但是,发现有问题啊啊啊,store的更新是惰性的,

chatgpt说,可以给他强制更新,但好像又不太好,如果需要所有的历史长度,或许可以

this.forceUpdate(); // 强制重新渲染组件

或者包一个connect

export default connect(mapStateToProps, mapDispatchToProps, null, { shouldComponentUpdate: () => true })(Counter);

(未验证)

后来请教了下大神,实际上可以在组件销毁方法里去监听,原理和去监听路由一样的,而且这样可以更好的~去维护,不用浪费全局的router资源。

【销毁组件的方法就更简单了......直接useEffect里return出去就行,用的少竟然忘记掉了】

这样每次读去到type的时候,可以再去取消掉,有点类似订阅的机制,总之更好管理。

感叹一下还是得

相关推荐
中工钱袋30 分钟前
Vue 中地址栏参数与 HTTP 请求参数的同步问题
前端·vue.js·http
zzlyx9934 分钟前
设备管理系统功能与.NET+VUE(IVIEW)技术实现
前端·vue.js·view design
秋月华星2 小时前
【flutter】TextField输入框工具栏文本为英文解决(不用安装插件版本
前端·javascript·flutter
千里码aicood3 小时前
[含文档+PPT+源码等]精品基于Python实现的校园小助手小程序的设计与实现
开发语言·前端·python
青红光硫化黑3 小时前
React基础之React.memo
前端·javascript·react.js
大麦大麦4 小时前
深入剖析 Sass:从基础到进阶的 CSS 预处理器应用指南
开发语言·前端·css·面试·rust·uni-app·sass
m0_616188495 小时前
Vue3 中 Computed 用法
前端·javascript·vue.js
六个点5 小时前
图片懒加载与预加载的实现
前端·javascript·面试
Patrick_Wilson6 小时前
🔥【全网首篇】30分钟带你从0到1搭建基于Lynx的跨端开发环境
前端·react.js·前端框架
Moment6 小时前
前端 社招 面筋分享:前端两年都问些啥 ❓️❓️❓️
前端·javascript·面试