我有一个路由器文件,其中的路由嵌套在索引组件下。 但是,我需要其他组件,我不想将其嵌套在任何组件下,但我想使用它来重定向到“ /”本地路由。
如果我使用Div标签,则它与我的模板搞混了。 我要添加登录组件-交换机标签内的路由。 如果我不这样做,我会得到React只有一个子错误。
有人知道如何进行嵌套路线和非嵌套路线吗?请帮忙。
这是我的路由器文件。
import React, { Component } from 'react';
import './App.css';
import { Provider } from 'react-redux';
import store from './store/store';
import { Router, Route , Switch } from 'react-router-dom';
import Index from './actions/indexToggle/indexActions';
import FirstDashboard from './_layouts/views/firstDashboard';
import SecondDashboard from './_layouts/views/secondDashboard';
import ThirdDashboard from './_layouts/views/thirdDashboard';
import FourthDashboard from './_layouts/views/fourthDashboard';
import history from './history';
import FifthDashboard from './_layouts/views/fifthDashboard';
import Login from './_layouts/views/Login/login';
const Main = () => (
<Provider store={store}>
<Router history={history}>
<Switch>
<Index>
<Route exact path='/overview1' component={FirstDashboard} />
<Route exact path='/overview2' render={(props) => <SecondDashboard {...props} show="show" /> } />
<Route exact path='/overview3' component={ThirdDashboard} />
<Route exact path='/overview4' component={FourthDashboard} />
<Route exact path='/overview5' component={FifthDashboard} />
</Index>
<Route path='/login' component={Login} />
</Switch>
</Router>
</Provider>
)
export default Main;
答案 0 :(得分:1)
这就是我所做的。参见DEMO。
我不想因为这个而感到困惑,所以我选择一种简单的方法。
routes.js
import Home from "./pages/Home";
import ComplexPath from "./pages/ComplexPath";
import Login from "./pages/Login";
export default [
{
path: "/",
component: Home,
withHeaderSidenav: true
},
{
path: "/yet/another/complex/path",
component: ComplexPath,
withHeaderSidenav: true
},
{
path: "/login",
component: Login,
withHeaderSidenav: false
}
];
然后,只需map
条路线即可。
App.js
import React from "react";
import { Switch, Route } from "react-router-dom";
import BaseLayout from "./BaseLayout";
import routes from "./routes";
export default class extends React.Component {
state = {
withHeaderSidenav: true
};
showHeaderSidenav = (withHeaderSidenav = true) => {
this.setState({ withHeaderSidenav });
};
render() {
return (
<BaseLayout withHeaderSidenav={this.state.withHeaderSidenav}>
<Switch>
{routes.map(route => (
<Route
exact
key={route.path}
path={route.path}
render={() => (
<route.component
showHeaderSidenav={() =>
this.showHeaderSidenav(route.withHeaderSidenav)
}
/>
)}
/>
))}
</Switch>
</BaseLayout>
);
}
}
每个页面都有一个HOC,用于处理布局更改。请参见演示项目中的pages/withBase.js
。