react中(reactv18)+router(v6)js获取router实例及技巧
`
/**
- 获取react-router实例对象,在js中跳转页面
*/
// useEffect 的函数会在组件渲染到屏幕之后执行
// useLayoutEffect则是在DOM结构更新后、渲染前执行,相当于有一个防抖效果(不推荐)
import { useState, useEffect } from 'react'
import { createBrowserHistory, createHashHistory } from 'history'
import { Router } from 'react-router-dom'
// 1. history
// export const history = createBrowserHistory();
// 2. hash
// == 创建路由实例对象 =》作用:js中使用跳转页面 ==
export const history = createHashHistory()
// == 函数组件 => 作用:包裹根组件,注册history
export const HistoryRouter = ({ history, children }) => {
const [state, setState] = useState({
action: history.action,
location: history.location
})
useEffect(() => {
history.listen(setState)
}, [history])
return <Router children={children} navigator={history} {...state} />
}
记得在index.js入口使用实例包裹而不是import { HashRouter } from "react-router-dom"中的HashRouter
import { HistoryRouter, history } from '@/router/history'
HistoryRouter history={history}
`

本文来自博客园,作者:jialiangzai,转载请注明原文链接:https://www.cnblogs.com/zsnhweb/articles/16796283.html

浙公网安备 33010602011771号