当前位置: 首页 > news >正文

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

感叹一下还是得

http://www.lryc.cn/news/397445.html

相关文章:

  • 基于深度学习的点云降噪
  • 数据结构-二叉搜索树与红黑树
  • 52771-009P 同轴连接器
  • 鸿蒙语言基础类库:【@ohos.util.Vector (线性容器Vector)】
  • 使用Python绘制堆积面积图
  • 代码还原动态调试之 pstree 乘法变加法
  • C++:获取当前可执行核心数(开辟线程)
  • 【简历】吉林某985大学:JAVA实习简历指导,面试通过率相当低
  • C#中的MD5摘要算法与哈希算法
  • 使用 python 构建企业级高可用海量爬虫调度系统
  • IDEA常用技巧荟萃:精通开发利器的艺术
  • GD32F303之CAN通信
  • postgres 的dblink使用,远程连接数据库
  • 短视频矩阵系统是什么?怎么搭建短视频矩阵系统?一文了解矩阵模式
  • 查看centos硬盘大小
  • 2024 年 6 月公链行业研报:市场回调,比特币和以太坊 Layer 2 表现各异
  • SAP S4 销售组的定义和分配
  • 实时数仓和离线数仓的区别是什么,企业该如何选择合适的数仓架构?
  • 花所Flower非小号排名20名下载花所Flower
  • 程序员有哪些职位?
  • python+Selenium自动化之免登录(cookie及token)
  • Web安全:SQL注入
  • 【LLM-驯化】成功配置多模态大模型InternLM-XComposer微调环境
  • C++·继承
  • 2024最适合小白的Midjourney教程,值得收藏!
  • MVC 返回集合方法,以及分页
  • 昇思MindSpore学习笔记6-05计算机视觉--SSD目标检测
  • vb.netcad二开自学笔记9:界面之ribbon
  • 学习笔记——动态路由——OSPF链路状态通告(LSA)
  • 模拟防止重复提交