【发布时间】:2021-10-26 09:45:04
【问题描述】:
我正在使用 React 构建一个应用程序并使用 react-router-dom。
我当前的设置在大多数情况下都有效,但如果路线未知并且我认为我没有使用最佳做法,则无法渲染。
这就是我所拥有的:
index.js
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<Suspense fallback={<div>Loading...</div>}>
<Route path="/" component={Main} />
</Suspense>
</BrowserRouter>
</Provider>,
document.getElementById('root')
);
然后在我的 Main.js 类组件中,如果用户未通过身份验证,我会渲染登录页面和this.props.history.push('/login')。如果用户通过身份验证,我有以下路线:
{this.props.location.pathname === '/' || this.props.location.pathname.endsWith('dashboard') && <Dashboard />}
<Switch>
{
userAdmin &&
<React.Fragment>
<Route exact path="/users" component={Users} />
<Route path="/users/:id" component={User} />
</React.Fragment>
}
{
productAdmin &&
<React.Fragment>
<Route exact path="/products" component={Products} />
<Route path="/products/:id" component={Product} />
</React.Fragment>
}
<Route component={Dashboard} />
</Switch>
如果路由不匹配,我想将经过身份验证的用户重定向到/ 并呈现Dashboard。
我添加了<Route component={Dashboard} />,它不起作用。
我也试过<Redirect to="/dashboard" />,但它什么也没做。
我尝试删除开关,然后它似乎按预期工作,但每当我尝试直接访问任何其他现有路由时它也会重定向。
我应该如何正确设置?
【问题讨论】: