如何在React中无额外逻辑将根索引路由重定向到自定义路由
React根路由重定向实现方案
你当前代码存在两个问题:
<Redirect>组件无需传入component属性,该组件仅负责路由跳转逻辑- 缺少
/dashboard路径对应的路由规则,跳转后无法匹配到组件会导致页面空白
修改后的完整代码:
import React from "react"; import { BrowserRouter as Router, Route, Switch, Redirect, } from "react-router-dom"; import history from "./history"; import DashboardScreen from "./components/screens/DashboardScreen"; class App extends React.Component { render() { return ( <Router history={history}> <Switch> <Route exact path='/'> <Redirect to='/dashboard' /> </Route> {/* 新增dashboard路径对应路由 */} <Route exact path='/dashboard' component={DashboardScreen} /> <Route exact path='/passwords' component={DashboardScreen} /> <Route exact path='/notes' component={DashboardScreen} /> <Route exact path='/addresses' component={DashboardScreen} /> </Switch> </Router> ); } } export default App;
核心修改点:
- 移除
<Redirect>上冗余的component={DashboardScreen}属性 - 新增
/dashboard路径的路由配置,绑定DashboardScreen组件
修改后启动项目,访问根路径http://localhost:3000/会自动重定向到http://localhost:3000/dashboard,页面正常渲染仪表盘内容,无需额外鉴权逻辑。
内容的提问来源于stack exchange,提问作者Toan Lam
相关产品推荐
相关产品推荐

