TypeScript集成React Router遇hashHistory导出错误求助
hashHistory未导出的问题 Hey there, let's break down what's going on here and fix this error quickly!
问题根源
React Router 4.x underwent a full architecture rewrite—the hashHistory you're looking for is an API from v3 and earlier versions, and it was completely removed in v4. Instead, v4 switched to a component-based routing approach. That's why you can't find it in the v4 @types/react-router definitions, and the v3 folder you saw is just for projects still using the older version.
两种修复方案(推荐第一种)
1. 改用React Router 4.x的组件式写法(推荐)
For browser-based projects, you should use the react-router-dom package (which depends on react-router). Use the HashRouter component to achieve hash-mode routing, replacing the old hashHistory approach.
First, make sure you have the necessary packages and type definitions installed:
npm install react-router-dom @types/react-router-dom # Or with yarn yarn add react-router-dom @types/react-router-dom
Then update your code to import HashRouter from react-router-dom and wrap your routes with it:
import React from 'react'; import ReactDOM from 'react-dom'; import { HashRouter, Route } from 'react-router-dom'; import Home from './Home'; // Your home component ReactDOM.render( <HashRouter> <Route path="/" component={Home} /> {/* Add other route configurations here */} </HashRouter>, document.getElementById('root') );
If you want native browser history mode (URLs without the #), just replace HashRouter with BrowserRouter.
2. Roll back to React Router v3 (not recommended)
If you absolutely need to keep using hashHistory for legacy reasons, install the matching v3 versions:
npm install react-router@3.x @types/react-router@3.x # Or with yarn yarn add react-router@3.x @types/react-router@3.x
This isn't advised though—v3 is no longer maintained, and v4+'s component-based approach is far more flexible and aligned with React's core principles.
Quick Tip
React Router 4+ splits its functionality into three packages: react-router (core logic), react-router-dom (browser-specific tools), and react-router-native (for React Native). Always use react-router-dom for browser projects instead of directly using react-router.
内容的提问来源于stack exchange,提问作者David Martin




