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的时候,可以再去取消掉,有点类似订阅的机制,总之更好管理。

感叹一下还是得

相关推荐
ai小鬼头1 小时前
百度秒搭发布:无代码编程如何让普通人轻松打造AI应用?
前端·后端·github
漂流瓶jz1 小时前
清除浮动/避开margin折叠:前端CSS中BFC的特点与限制
前端·css·面试
前端 贾公子2 小时前
在移动端使用 Tailwind CSS (uniapp)
前端·uni-app
散步去海边2 小时前
Cursor 进阶使用教程
前端·ai编程·cursor
清幽竹客2 小时前
vue-30(理解 Nuxt.js 目录结构)
前端·javascript·vue.js
weiweiweb8882 小时前
cesium加载Draco几何压缩数据
前端·javascript·vue.js
幼儿园技术家2 小时前
微信小店与微信小程序简单集成指南
前端
我不吃饼干9 天前
鸽了六年的某大厂面试题:你会手写一个模板引擎吗?
前端·javascript·面试
涵信9 天前
第一节 布局与盒模型-Flex与Grid布局对比
前端·css
我不吃饼干9 天前
鸽了六年的某大厂面试题:手写 Vue 模板编译(解析篇)
前端·javascript·面试