react-router-redux 5.x中如何使用哈希路由?相关资料缺失求指导
Got it, I know it's confusing since ConnectedRouter took over from HashRouter in v5.x, but setting up hash routing is totally doable—you just need to pair ConnectedRouter with a hash-based history instance. Let's break it down step by step:
Step 1: Install Required Dependencies
First, make sure you have the compatible versions (react-router-redux 5.x works with react-router v4/v5, so you'll need history@4.x instead of the latest v5):
npm install react-router-redux@5.x react-router-dom history@4.x # or with yarn yarn add react-router-redux@5.x react-router-dom history@4.x
Step 2: Create a Hash History Instance
Instead of relying on HashRouter's built-in history, you'll create your own hash-based history using the history package:
// src/history.js import { createHashHistory } from 'history'; export const history = createHashHistory();
Step 3: Configure Your Redux Store
Add the routerMiddleware from react-router-redux to your store, passing in the hash history instance we just created:
// src/store.js import { createStore, applyMiddleware, compose } from 'redux'; import { routerMiddleware } from 'react-router-redux'; import rootReducer from './reducers'; import { history } from './history'; // Add the router middleware to sync routing with redux const middleware = [routerMiddleware(history)]; // Set up dev tools (optional but helpful for debugging) const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const store = createStore( rootReducer, composeEnhancers(applyMiddleware(...middleware)) ); export default store;
Step 4: Wrap Your App with ConnectedRouter
Replace HashRouter with ConnectedRouter, pass in your hash history, then set up routes like you would with regular react-router:
// src/App.js import React from 'react'; import { ConnectedRouter } from 'react-router-redux'; import { Route, Switch } from 'react-router-dom'; import { history } from './history'; import Home from './components/Home'; import About from './components/About'; function App() { return ( <ConnectedRouter history={history}> <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> </Switch> </ConnectedRouter> ); } export default App;
Step 5: Wrap Everything with Redux Provider
Don't forget to wrap your App with the Redux Provider so the router can access the store:
// src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import store from './store'; import App from './App'; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
That's all! Your app will now use hash routing (you'll see /#/ in the URL) while maintaining full integration with Redux via react-router-redux 5.x.
内容的提问来源于stack exchange,提问作者mq7

