React中自定义history后<Link>失效,如何同时使用二者?
Hey there! I totally get where you're coming from—mixing custom history for Redux actions with React Router's <Link> can feel tricky at first, but let's get this sorted out step by step.
First, Confirm Your Custom History Setup
Make sure you're creating your history instance correctly using the history library. Here's the standard approach:
// history.js import { createBrowserHistory } from 'history'; export default createBrowserHistory();
Stick with createBrowserHistory unless you specifically need hash-based routing—this is a common gotcha that can break navigation silently.
Use the Right Router Component
In React Router v4, if you're using a custom history instance, you must use the base Router component (not BrowserRouter). BrowserRouter generates its own internal history instance, which will override yours and create conflicts with <Link>.
Here's how to set it up properly in your App.js:
// App.js import React from 'react'; import Router from 'react-router-dom/Router'; // Note: not BrowserRouter import { Switch, Route, Link } from 'react-router-dom'; import customHistory from './history'; import Home from './components/Home'; import About from './components/About'; function App() { return ( <Router history={customHistory}> {/* Navigation bar with Link components */} <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> </nav> {/* Switch to fix page stacking */} <Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> </Switch> </Router> ); } export default App;
The Switch component is non-negotiable here—it only renders the first route that matches the current URL, which eliminates the "page stacking" issue you mentioned. Always wrap all your routes inside a single Switch (never multiple ones!) to prevent overlapping route renders.
Using Custom History in Redux Actions
Now you can safely use your custom history instance directly in your Redux actions to trigger navigation:
// actions/navigationActions.js import customHistory from '../history'; export const navigateToAbout = () => { return (dispatch) => { // Your Redux logic here (e.g., dispatch state updates) dispatch({ type: 'NAVIGATION_INITIATED' }); // Use custom history to navigate customHistory.push('/about'); }; };
Common Pitfalls to Avoid
- Multiple Router Instances: Never nest
Routercomponents anywhere in your app—this will cause unpredictable navigation behavior. - Missing
exactProp: For your home route (/), always add theexactprop so it doesn't match every route that starts with/(like/about). - Incorrect Imports: Double-check that you're importing
Routerfromreact-router-dom/Router, not the defaultBrowserRouter.
That should fix both your <Link> navigation issue and the page stacking problem. Let me know if you hit any other snags!
内容的提问来源于stack exchange,提问作者Diego Flores

