Essential React Router Knowledge and Tips
This article explains the core concepts, basic usage, nested routing, parameter handling, Switch behavior, browser and hash modes, underlying path‑to‑regexp dependency, and integration with Dva, providing practical code examples and best‑practice recommendations for React Router in modern single‑page applications.
Introduction
When building new pages you inevitably need to design URLs and routing; beyond simple path strings, you can adopt more elegant designs and understand how routes cooperate with components. This guide uses React Router as a concrete example to collect useful knowledge points.
React‑Router Basic Usage
The typical way to control routing in a React SPA is to use React‑Router , which manages the URL and switches components accordingly.
import { Router, Route } from 'react-router';
render(
,
document.getElementById('app')
);Older versions allowed direct nesting of <Route> elements, but version 4 changed the rendering logic to follow React’s component‑centric philosophy.
Nested Routes (Modern Approach)
<Route
path="/"
render={() => (
Outer
} />
Inner
} />
Other
} />
)}
/>Visiting /in now displays both “Outer” and “Inner”, while /others shows “Outer” and “Other”.
Route Parameter Tips
Scenario 1 – Simple Parameters
Case A: Path parameters
path="/book/:id"Using a colon followed by a name injects the value into the URL; a change in id creates a new route.
Case B: Query parameters
<Link to="/book?id=111" />
// or
<Link to={{ pathname: '/book', search: '?id=111' }} />When the query changes, the component updates (componentDidUpdate runs) but is not remounted.
Case C: State‑based hidden parameters
<Link to={{ pathname: '/book', state: { id: 111 } }} />Parameters are stored in location.state ; they disappear on page refresh, so this method is discouraged for persistent data.
Scenario 2 – Constrained Parameters
path="/book/:pageType(edit|detail|add)"The regular‑expression segment ensures only the listed values are accepted; otherwise a 404 is triggered.
Scenario 3 – Optional Parameters
path="/book/:pageType(edit|detail|add)/:id?"The trailing ? makes id optional, allowing the same component to serve both add (no id) and edit/detail (with id) pages.
Scenario 4 – Numeric Only Parameters
path="/book/:id(\d+)"If id is not a number, the router returns a 404.
Underlying Dependency
All these patterns rely on the path-to-regexp library.
var pathToRegexp = require('path-to-regexp');
var keys = [];
var re = pathToRegexp('/foo/:bar', keys);
// re => /^\/foo\/([^\/]+?)\/?$/i
// keys => [{ name: 'bar', ... }]Retrieving Route Parameters
Parameters defined in the path are accessible via this.props.match.params :
const { match } = this.props;
const { pageType } = match.params;Query strings can be read from this.props.location.search (or this.props.history.location , though the latter is less reliable). In hash‑mode URLs, the hash part is ignored by location.search , so you must use this.props.location provided by React‑Router.
Switch Component
<Switch> renders only the first matching <Route> . Order matters: place more specific routes after generic ones to avoid premature matches.
<Switch>
Image
} />
Book
} />
</Switch>When visiting /router/book , the generic /router/:type matches first, so “Book” is not rendered unless the generic route is placed later.
Router Fundamentals
Routing controls URL changes; the router reacts to those changes by rendering the appropriate component. URLs can be in Browser mode (no # ) or Hash mode (with # ).
Browser Mode
Navigation via back/forward triggers the popstate event, which updates the router’s location state.
const handlePopState = (event) => {
const location = getDOMLocation(event.state);
const action = 'POP';
transitionManager.confirmTransitionTo(location, action, getUserConfirmation, (ok) => {
if (ok) setState({ action, location });
else revertPop(location);
});
};Programmatic navigation (e.g., history.push ) creates a new location, calls window.history.pushState , and then updates the router state.
const push = (path, state) => {
const action = 'PUSH';
const location = createLocation(path, state, createKey(), history.location);
transitionManager.confirmTransitionTo(location, action, getUserConfirmation, (ok) => {
const href = createHref(location);
if (canUseHistory) {
globalHistory.pushState({ key: location.key, state: location.state }, null, href);
setState({ action, location });
} else {
window.location.href = href;
}
});
};Hash Mode
Hash changes fire the hashchange event, which the router listens to and updates the view similarly.
window.addEventListener('hashchange', function (e) {
// handle hash change
});Programmatic navigation in hash mode ultimately modifies window.location.hash (or window.location.replace for replace).
Dva Integration
In projects using Dva, Link and Route are imported from dva/router . Dva does not alter React‑Router’s behavior; it simply provides a wrapper that forwards the standard API.
Custom Router Handling in Our Projects
We split route definitions into per‑module configuration files and aggregate them via a custom Webpack plugin, generating a unified router-config.js . This keeps large codebases manageable.
We also migrated from hash‑mode to browser‑mode for better SEO and to avoid anchor conflicts, using history/createBrowserHistory with a basename :
import createHistory from 'history/createBrowserHistory';
const app = dva({
history: createHistory({ basename: '/book-center' }),
onError,
});Redirects and Nginx rules are added to handle legacy hash URLs and 404 scenarios.
References
“彻底弄懂 React‑Router 路由原理” – https://blog.csdn.net/zl_alien/article/details/109231294
React‑Router v4 路由规则解析 – https://www.cnblogs.com/pqjwyn/p/9936153.html
二级动态路由的解决方案 – https://aibokalv.oschina.io/myarticle/2017/04/01/20170401二级动态路由的解决方案/
政采云技术
ZCY Technology Team (Zero), based in Hangzhou, is a growth-oriented team passionate about technology and craftsmanship. With around 500 members, we are building comprehensive engineering, project management, and talent development systems. We are committed to innovation and creating a cloud service ecosystem for government and enterprise procurement. We look forward to your joining us.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.