子路线未显示React-router

时间:2018-09-22 18:41:42

标签: reactjs react-router

我分开的路由到下面的不同文件是代码。当我尝试导航/ child路线时,什么都没有显示。这浪费了我的时间

routes.js:-

import  App  from "./components/app";
import  Post  from "./components/post";

export const routes = [
    {
      component: App,
      path: '/',
      childRoutes: [{
        path: 'child',
        component: Post
    }]
    },
    {
        component: Post,
        path: '/post',
        childRoutes: [{
          path: 'dashboard',
          component: App
      }]
      }
  ];
index.js:-
 <Router>
      <div>
        <Switch>


         {routes.map(props => <Route exact {...props}>{props.childRoutes.map(e=><Route exact {...e}/>)}</Route>)} 

        </Switch>
      </div>
    </Router>

2 个答案:

答案 0 :(得分:1)

您不能在react-router v4.x中嵌套这样的路由(我偏爱v3.0.4的众多原因之一)。您必须指向一个单独的父组件,然后该组件具有单独的Route来确定要安装哪个组件 OR 并用子对象填充Route的{​​{1}}方法路线。

工作示例:https://codesandbox.io/s/6zn2103rxw(渲染方法-不太干净)

工作示例:https://codesandbox.io/s/ll33rmz0n7(映射的路线-还是不太干净)

工作示例:https://codesandbox.io/s/8knzzrq5k8(父组件-最容易阅读和理解)

routes / index.js

render

components / FullRoster.js (父级)

import React from "react";
import { Route } from "react-router-dom";
import Home from "../components/Home";
import Header from "../components/Header";
import FullRoster from "../components/FullRoster";
import Schedule from "../components/Schedule";

export default () => (
  <div>
    <Header />
    <Route exact path="/" component={Home} />
    <Route path="/roster" component={FullRoster} />
    <Route path="/schedule" component={Schedule} />
  </div>
);

components / ShowRoster.js (子级)

import React from "react";
import { Route } from "react-router-dom";
import ShowPlayerRoster from "./ShowPlayerRoster";
import ShowPlayerStats from "./ShowPlayerStats";

export default ({ match }) => (
  <div>
    <Route exact path={match.path} component={ShowPlayerRoster} />
    <Route path={`${match.path}/:id`} component={ShowPlayerStats} />
  </div>
);

components / ShowPlayerStats.js (子级)

import map from "lodash/map";
import React from "react";
import { Link } from "react-router-dom";
import PlayerAPI from "../api";

export default () => (
  <div style={{ padding: "0px 20px" }}>
    <ul>
      {map(PlayerAPI.all(), ({ number, name }) => (
        <li key={number}>
          <Link to={`/roster/${number}`}>{name}</Link>
        </li>
      ))}
    </ul>
  </div>
);

答案 1 :(得分:0)

您还需要用前斜杠声明子路径:

childRoutes: [{
   path: '/child',
   component: Post
}]