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

感叹一下还是得

相关推荐
excel18 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel19 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼21 小时前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping21 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙1 天前
[译] Composition in CSS
前端·css
白水清风1 天前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix1 天前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户22152044278001 天前
new、原型和原型链浅析
前端·javascript
阿星做前端1 天前
coze源码解读: space develop 页面
前端·javascript
叫我小窝吧1 天前
Promise 的使用
前端·javascript