React Router v4搭配Webpack构建后路由失效问题求助
兄弟,我之前踩过几乎一模一样的坑!结合你用React Router v4 + react-router-redux的场景,大概率是这几个环节出了问题,咱们一步步来排查解决:
1. 先确认路由组件的选型:用BrowserRouter而非HashRouter
首先检查你项目里用的是不是BrowserRouter——如果不小心用了HashRouter,构建后很容易出现URL不更新的情况。另外,部署时服务器必须配置支持SPA路由(比如Nginx要加try_files $uri $uri/ /index.html;,Apache要配置RewriteRule),否则手动输入/products这类路由时,服务器会找不到对应文件,最终重定向到首页。
补充:如果是部署在GitHub Pages这类静态托管平台,可能需要改用
HashRouter,但这时候URL会带#,和你描述的“URL始终显示根路径”情况不太匹配,所以优先确认是BrowserRouter。
2. 检查react-router-redux的配置是否正确
react-router-redux在配合React Router v4时,配置细节很容易出错,重点看这几点:
- 必须用
ConnectedRouter包裹你的路由组件,而不是直接用BrowserRouter - 要确保
routerMiddleware已经正确添加到Redux store的middleware队列中 - 派发
pushaction时,要确认是通过react-router-redux提供的action creator,而非自己手写的
给你贴个正确配置的示例参考:
// store.js import { createStore, applyMiddleware } from 'redux'; import { routerMiddleware } from 'react-router-redux'; import createHistory from 'history/createBrowserHistory'; import rootReducer from './reducers'; // 创建独立的history实例 export const history = createHistory(); // 注入history到路由中间件 const middleware = routerMiddleware(history); export const store = createStore( rootReducer, applyMiddleware(middleware) ); // App.jsx import { Provider } from 'react-redux'; import { ConnectedRouter } from 'react-router-redux'; import { history, store } from './store'; import { Switch, Route } from 'react-router-dom'; import Home from './pages/Home'; import Products from './pages/Products'; function App() { return ( <Provider store={store}> <ConnectedRouter history={history}> <Switch> <Route exact path="/" component={Home} /> <Route path="/products" component={Products} /> <Redirect to="/" /> {/* 这个要放在最后,仅当无匹配路由时重定向 */} </Switch> </ConnectedRouter> </Provider> ); }
3. 排查全局重定向逻辑的顺序
看看你的路由配置里,<Redirect to="/" />是不是放在了错误的位置——如果它在<Route path="/products" />前面,会直接把所有路由请求都重定向到首页,手动输入路径自然会失效。一定要把全局重定向放在所有路由规则的最后。
4. 检查组件内的跳转逻辑
应用内点击按钮操作正常但URL不变,大概率是跳转方式错了:
- 不要用普通的
<a href="/products">,会导致页面刷新,而且URL可能被服务器拦截重定向 - 优先用react-router提供的
<Link to="/products">或<NavLink to="/products">组件 - 如果是手动触发跳转(比如按钮点击事件),要确保调用的是react-router-redux映射过来的
push方法,比如:import { connect } from 'react-redux'; import { push } from 'react-router-redux'; class ProductButton extends React.Component { handleClick = () => { this.props.push('/products'); }; render() { return <button onClick={this.handleClick}>去商品页</button>; } } export default connect(null, { push })(ProductButton);
5. 确认部署的基础路径
如果你的应用是部署在域名的子路径下(比如https://your-site.com/my-app/),必须给ConnectedRouter设置basename属性,否则构建后的路由会找不到正确的根路径,导致自动重定向到首页:
<ConnectedRouter history={history} basename="/my-app"> {/* 路由配置 */} </ConnectedRouter>
内容的提问来源于stack exchange,提问作者maoooricio

