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

感叹一下还是得

相关推荐
琹箐7 分钟前
ant-design4.xx实现数字输入框; 某些输入法数字需要连续输入两次才显示
前端·javascript·anti-design-vue
程序员-小李8 分钟前
VuePress完美整合Toast消息提示
前端·javascript·vue.js
Uyker1 小时前
从零开始制作小程序简单概述
前端·微信小程序·小程序
Dontla4 小时前
为什么React列表项需要key?(React key)(稳定的唯一标识key有助于React虚拟DOM优化重绘大型列表)
javascript·react.js·ecmascript
EndingCoder5 小时前
React从基础入门到高级实战:React 实战项目 - 项目三:实时聊天应用
前端·react.js·架构·前端框架
阿阳微客6 小时前
Steam 搬砖项目深度拆解:从抵触到真香的转型之路
前端·笔记·学习·游戏
德育处主任Pro7 小时前
『React』Fragment的用法及简写形式
前端·javascript·react.js
CodeBlossom7 小时前
javaweb -html -CSS
前端·javascript·html
打小就很皮...8 小时前
HBuilder 发行Android(apk包)全流程指南
前端·javascript·微信小程序
集成显卡9 小时前
PlayWright | 初识微软出品的 WEB 应用自动化测试框架
前端·chrome·测试工具·microsoft·自动化·edge浏览器