【问题标题】:Upgrading to react-router 5 and history升级到 react-router 5 和历史
【发布时间】:2021-09-24 19:50:25
【问题描述】:

我尝试从反应路由器 3.2.6 迁移到 5.2.1 我也用过 react-router-redux。和react-router 5x不兼容,看来我们需要使用connected-react-router

在我的 app.tsx 中

import {hashHistory, Router} from "react-router";
import {synchHistoryWithStore} from "react-router-redux";

async function initApp(){
  
  const store = await configureStore(
    hashHistory
  );

  const history = syncHistoryWithStore(hashHistory, store);

  hashHistory.listen((event: any) => {

  });

  ReactDom.render(
     (
     ...
     <Router history={history}
          {routes}
     </Router>
     ....
     ),
     document.getElementById("app"),
     );

}

只是不知道如何迁移。 在我的商店里我需要用什么来替换 hashHistory?

【问题讨论】:

    标签: reactjs react-redux react-router


    【解决方案1】:

    你的减少/索引

    import { createStore, combineReducers, applyMiddleware, compose } from "redux";
    import { connectRouter, routerMiddleware  } from "connected-react-router";
    import thunk from "redux-thunk";
    import { createBrowserHistory } from "history";
    
    export const history = createBrowserHistory();
    const middlewares = [thunk, routerMiddleware(history)];
    
    const rootReducer = (history) =>
      combineReducers({
        router: connectRouter(history),
        ...others-reducers
      });
    
    const generateStore = () => {
      const store = createStore(
        rootReducer(history),
        compose(applyMiddleware(...middlewares))
      );
      if (module.hot) {
        module.hot.accept("./", () => {
          store.replaceReducer(rootReducer(history));
        });
      }
    
      return store;
    };
    
    export default generateStore;
    

    现在在您的应用中

    import React from "react";
    import { Provider } from "react-redux";
    import { ConnectedRouter } from "connected-react-router";
    import generateStore, { history } from "./reducers";
    
    const store = generateStore();
    
    const App = () => {
      return (
        <Provider store={store}>
          <ConnectedRouter history={history}>
            <p>mi-app<p>
          </ConnectedRouter>
        </Provider>
      );
    };
    
    export default App;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-26
      • 2017-12-29
      • 2021-10-24
      • 1970-01-01
      • 2018-05-14
      • 2016-08-29
      • 2023-01-20
      • 2016-09-30
      相关资源
      最近更新 更多