react-router-dom使用带history prop的Router组件跳转出现白页问题
React Router 传入history prop跳转白页故障解决方案
常见根因及修复方案
1. React Router v6版本API不兼容
- React Router v6 已经移除了基础
Router组件直接接收history属性的语法,沿用v5的写法会导致路由无法监听history变化,触发白页。 - 修复方式:使用v6提供的
unstable_HistoryRouter替代基础Router组件:
import { unstable_HistoryRouter as HistoryRouter } from 'react-router-dom'; import { createBrowserHistory } from 'history'; const customHistory = createBrowserHistory(); // 路由根组件写法 <HistoryRouter history={customHistory}> <div> <Switch> <PrivateRoute exact path="/" component={Home} /> <Route path="/signin" component={SignIn} /> <Route path="/signup" component={SignUp} /> <Redirect from="*" to="/" /> </Switch> </div> </HistoryRouter>
2. React Router v5与history库版本不匹配
- v5版本的react-router-dom仅适配
history@4.x版本,如果你安装了history@5.x版本会出现事件监听失效、跳转后无渲染的白页问题。 - 修复方式:降级history到适配版本:
npm install history@4.10.1 # 或yarn安装 yarn add history@4.10.1
3. 私有路由PrivateRoute逻辑错误
- 检查
PrivateRoute组件的鉴权逻辑是否存在问题,比如未登录时跳转路径错误、循环跳转、props未透传都可能触发白页。 - v5版本标准PrivateRoute实现参考:
const PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={props => // 替换为你的实际鉴权逻辑 window.localStorage.getItem('authToken') ? ( <Component {...props} /> ) : ( <Redirect to={{ pathname: '/signin', state: { from: props.location } }} /> ) } /> );
内容的提问来源于stack exchange,提问作者Cristhian Benitez
相关产品推荐
相关产品推荐

