2 回答

TA貢獻2080條經(jīng)驗 獲得超4個贊
a 的所有子元素<Switch>都應(yīng)該是<Route>或<Redirect>元素。只會呈現(xiàn)與當前位置匹配的第一個孩子。
https://reacttraining.com/react-router/web/api/Switch/children-node
因為您使用的是 Fragment,所以您正在添加不受支持的其他子項,Switch因此您的代碼不會呈現(xiàn)。
您應(yīng)該按如下方式切換代碼,在不使用片段的情況下添加條件路由:
<Switch>
<Route
component={TestComponent}
key={TestComponentPath}
path={TestComponentPath}
exact
/>
{ exampleCondition &&
<Route
component={TestComponent2}
key={TestComponentPath2}
path={TestComponentPath2}
exact
/> }
{ exampleCondition &&
<Route
component={TestComponent3}
key={TestComponentPath3}
path={TestComponentPath3}
exact
/> }
<Redirect to={redirectUrl} />
</Switch>
如果您擔(dān)心重復(fù)代碼,您可以在您的代碼中添加額外的層,Route如下所示:
<Switch>
<Route
component={TestComponent}
key={TestComponentPath}
path={TestComponentPath}
exact
/>
{someCondition && [
<Route
component={TestComponent2}
key={TestComponentPath2}
path={TestComponentPath2}
exact
/>,
<Route
component={TestComponent3}
key={TestComponentPath3}
path={TestComponentPath3}
exact
/>
]}
<Redirect to={redirectUrl} />
</Switch>

TA貢獻2012條經(jīng)驗 獲得超12個贊
我喜歡<ProtectedRoute>組件的想法:
import { Component } from 'react';
import { Redirect, Route } from 'react-router-dom';
class ProtectedRoute extends Component<any> {
render() {
const { component: Component, allow, ...props } = this.props;
if (!allow) {
return <Redirect to={{ pathname: '/signin' }} />;
}
return <Route {...props} render={(props) => <Component {...props} />} />;
}
}
export default ProtectedRoute;
然后像下面這樣使用它:
<Router history={history}>
<Route path={yourRootPath} component={App} exact>
<Route path="home" component={Home} />
<Route path="about" component={About} />
<ProtectedRoute path="inbox" component={Inbox} allow={this.props.mail} />
<ProtectedRoute path="contacts" component={Contacts} allow={this.props.mail} />
</Route>
</Router>
我嘗試按照公認的答案使用數(shù)組,但沒有奏效,因為JSX 表達式必須有一個父元素(也許這曾經(jīng)在舊的 React 版本中工作),而且我不想重復(fù)代碼。
添加回答
舉報