我正在尝试让 React 应用程序与 React Router 和 Redux 正常工作,但我不断TypeError: Cannot read property 'location' of undefined
任何具有 redux 的组件。我正在使用connected-react-router
库在商店中注册路由器,但显然我做错了什么
store/configureStore.js
import { createStore, applyMiddleware, compose } from 'redux';
import reducer from '../reducers';
import { persistStore } from 'redux-persist';
import { createBrowserHistory } from 'history';
import { routerMiddleware } from "connected-react-router";
let _persistor;
let _store;
export const history = createBrowserHistory();
export const getStore = (props) => {
if (_store) {
return _store;
}
const initialState = (props) ? {...props} : {};
_store = createStore(
reducer,
initialState,
compose(
applyMiddleware(routerMiddleware(history)),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
),
);
_persistor = persistStore(_store);
return _store;
};
export const getPersistor = () => {
return _persistor;
};
减速器/索引器.js
import { combineReducers } from 'redux';
import { persistReducer } from 'redux-persist';
import Menu from './Menu';
import SelectedServices from './SelectedServices';
import { connectRouter } from 'connected-react-router'
import { history } from "../store/configureStore";
const rootReducer = (history) => combineReducers({
router: connectRouter(history),
menu: Menu,
selectedServices: SelectedServices,
});
const reducer = persistReducer(
{
key: 'root',
storage: require('localforage'),
whitelist: [],
},
rootReducer(history),
);
export default reducer;
经过三个小时的调试并阅读了有关每个connected-react-router
库,react-redux
库和react-router-dom
的更多信息,我发现了一行我跳过了几次,但最终我在package.json
中检查了它。目前:
v6.0.0 需要 React v16.4.0 和 React Redux v6.0。(它还不支持 React Redux v7.0。我们正在研究兼容性问题。
我用的是react-redux: v7.0.1
,这对我自己来说是一个真正的掌心。所以我降级到 v6,一切开始正常。