- 问题描述:加上
connected-react-router相关的配置后报如下错误:Uncaught TypeError: Cannot read properties of undefined (reading 'pathname') - 自己定位问题的相关尝试:既然报
pathname相关错误,那应该是与 路由有关, 于是去翻看了react-router-dom及connected-react-router相关的文档, 也 google 了一遍,最后还是没解决问题。 - 技术栈:react(17.0.2) + TS(4.4.4)
- 相关代码:
store.ts
import { createBrowserHistory } from "history";
import { createStore, applyMiddleware } from 'redux';
import createRootReducer from './reducers';
import { routerMiddleware } from 'connected-react-router';
export const history = createBrowserHistory()
const store = createStore(
createRootReducer(history),
// routerMiddleware 监听路由的变化时,dispath action
applyMiddleware(routerMiddleware(history))
)
export default store;
reducers.ts
import { connectRouter } from 'connected-react-router';
import { combineReducers } from 'redux';
import testReducer from './test.reducer';
import { History } from 'history'
const createRootReducer = (history: History) => combineReducers({
test: testReducer,
router: connectRouter(history)
});
export default createRootReducer;
index.ts
import { connectRouter } from 'connected-react-router';
import { combineReducers } from 'redux';
import testReducer from './test.reducer';
import { History } from 'history'
const createRootReducer = (history: History) => combineReducers({
test: testReducer,
router: connectRouter(history)
});
export default createRootReducer;
routes.ts
import React from 'react'
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './components/core/Home';
import Shop from './components/core/Shop';
const Routers = () => {
return (
<BrowserRouter>
<Routes>
<Route path='/' element={ <Home /> } />
<Route path='/shop' element={ <Shop /> } />
</Routes>
</BrowserRouter>
)
}
export default Routers
相关的版本依赖:
"@testing-library/jest-dom": "^5.15.0",
"@testing-library/react": "^11.2.7",
"@testing-library/user-event": "^12.8.3",
"@types/jest": "^26.0.24",
"@types/node": "^12.20.37",
"@types/react": "^17.0.34",
"@types/react-dom": "^17.0.11",
"@types/react-redux": "^7.1.20",
"@types/react-router-dom": "^5.3.0",
"antd": "^4.16.13",
"axios": "^0.24.0",
"connected-react-router": "^6.9.1",
"history": "^5.1.0",
"moment": "^2.29.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.6",
"react-router-dom": "^6.0.2",
"react-scripts": "4.0.3",
"redux": "^4.1.2",
"redux-devtools-extension": "^2.13.9",
"redux-saga": "^1.1.3",
"typescript": "^4.4.4",
"web-vitals": "^1.1.2"