connectedRouter 错误:在状态树中找不到路由器减速器,它必须安装在“路由器”下

IT技术 reactjs react-redux react-router
2021-05-01 00:43:29

我是 React.js 的新手,并且正在设置基础项目,当时我遇到了一个问题,即我的路由已更改但组件未加载。谷歌搜索后,我发现我需要使用 ConnectedRouter。在设置 ConnectedRouter 时,我收到控制台错误:在状态树中找不到路由器减速器,它必须安装在“路由器”下

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { ConnectedRouter, connectRouter, routerMiddleware } from "connected-react-router";
import { Provider } from "react-redux";
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import createSagaMiddleware from 'redux-saga';
import loginReducer from "./store/reducers/login";
import { watchLogin} from "./store/sagas";
import { history } from '../src/shared/history';
import { push } from 'react-router-redux';



import './index.css';
import App from './App';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const rootReducer = combineReducers({
    login: loginReducer
});
const routersMiddleware = routerMiddleware(history)
const sagaMiddleware = createSagaMiddleware();
const middlewares = [sagaMiddleware, routersMiddleware];

const store = createStore(
    connectRouter(history)(rootReducer),
    {},
    composeEnhancers(applyMiddleware(...middlewares))
);

sagaMiddleware.run(watchLogin);

const app = (
    <Provider  store={store}>
        <ConnectedRouter  history={history}>
            <App />
        </ConnectedRouter>
    </Provider>
);

ReactDOM.render(app, document.getElementById('root'));

4个回答

为了帮助未来解决这个问题,事实证明,根据链接的 github 讨论,该history软件包的5.0 版导致了问题,降级到 4.10.1 版为我解决了这个问题。

npm install history@4.10.1

https://github.com/ReactTraining/history/issues/803

https://github.com/ReactTraining/history/issues/804

router使用connectRouter添加您的减速器history

参考这个链接

https://www.npmjs.com/package/connected-react-router

import { connectRouter } from 'connected-react-router'
const rootReducer = combineReducers({
  login: loginReducer,
  router: connectRouter(history),
});

主要问题是history包的版本,react-router-dom v5需要使用history v4(最新版本是4.10.1)——history v5只兼容react-router-dom v6。

你忘记了:

router: connectRouter(history), 

在你的 combineReducers()