升级react-router至5版本时hashHistory替换及相关依赖适配咨询
react-router 3.x升5.x搭配connected-react-router迁移方案
核心问题解答
你配置store时,原来传入的hashHistory需要替换为手动通过history库的createHashHistory方法生成的hash模式history实例。react-router v5已经不内置hashHistory实现,需要单独安装history库生成对应实例。
1. 安装适配依赖
先安装两个必要的兼容包,注意版本匹配要求:
connected-react-router@6.x:适配react-router v5的状态同步库,替代原react-router-reduxhistory@4.x:不要安装5.x版本,和connected-react-router 6.x存在兼容性问题
2. 代码修改示例
app.tsx 修改
// 移除原react-router的hashHistory、react-router-redux的syncHistoryWithStore导入 import { Router } from "react-router-dom"; import { createHashHistory } from "history"; // 生成hash模式history实例,替代原react-router内置的hashHistory const history = createHashHistory(); async function initApp(){ // 配置store时直接传入你创建的history实例 const store = await configureStore(history); // 原syncHistoryWithStore调用可以删除,connected-react-router会自动处理store和history的同步 history.listen((event: any) => { // 原有监听逻辑保持不变 }); ReactDom.render( ( ... <Router history={history}> {routes} </Router> .... ), document.getElementById("app"), ); }
configureStore 内部逻辑修改
你需要调整store的reducer和中间件配置,接入connected-react-router的逻辑:
import { createStore, combineReducers, applyMiddleware } from "redux"; import { connectRouter, routerMiddleware } from "connected-react-router"; export default async function configureStore(history) { const rootReducer = combineReducers({ // 接入router状态的reducer,state的key必须为router router: connectRouter(history), // 其余原有业务reducer保持不变 ...yourOtherReducers }); const middlewares = [ // 接入路由中间件,处理路由相关action routerMiddleware(history), // 其余原有中间件(如redux-thunk、saga等)保持不变 ...yourOtherMiddlewares ]; const store = createStore( rootReducer, applyMiddleware(...middlewares) // 其余原有store配置(如初始状态、devTool配置等)保持不变 ); return store; }
3. 注意事项
- react-router v5的Router组件需要从
react-router-dom引入,不要直接从react-router引入 - 原有react-router-redux的所有导入和逻辑都可以直接移除
- 原项目中从store获取路由状态的逻辑,只需要把取值路径调整为
state.router.location即可,用法和之前基本一致
内容的提问来源于stack exchange,提问作者robert trudel
相关产品推荐
相关产品推荐

