React - Mapping out组件返回错误

时间:2017-08-20 23:24:35

标签: reactjs meteor react-router-dom

有一个我想要用很多页面构建的应用程序,我认为最好的方法是将所有页面的名称和路径放入一个单独的文件中,然后将每个页面映射为反对有长渲染中的组件列表。我唯一的问题是,当我尝试使用map函数时,它会返回一个错误Uncaught SyntaxError: Unexpected token < in JSON at position 1

routes.js

import React from "react";
import { withRouter, Switch, BrowserRouter, Route, Redirect, Link } from "react-router-dom";

import Login from "../ui/authentication/Login";
import Signup from "../ui/authentication/Signup";
import Home from "../ui/Home";
import { SubjectRoutes } from "../ui/subjectRoutes/subjectRoutes";
import Math from "../ui/subjectRoutes/routes/math"
import Science from "../ui/subjectRoutes/routes/science"
import NotFound from "../ui/NotFound";

export default class Routes extends React.Component{
  renderSubjectRoutes(subjects){
    console.log(SubjectRoutes)
    return subjects.map((subject) => {
      return <{subject.name} path={subject.path} />
    })
  }
  render(){
    return (
      <div>
        <BrowserRouter>
          <Switch>
            <Login path="/login" />
            <Signup path="/signup" />
            <Home path="/home"/>
            {this.renderSubjectRoutes(SubjectRoutes)}
            <NotFound />
          </Switch>
        </BrowserRouter>
      </div>
    )
  }
}

subjectRoutes.js

export const SubjectRoutes = [{
  name: "Science",
  path: "/science"
},{
  name:"Math",
  path:"/math"
}]

我也尝试过返回<Route component={subject.name} path={subject.path}>,但它会返回一个类似Warning: Failed prop type: Invalid prop component of type string supplied to Route, expected function.的警告。您是否知道任何可能的解决方案来映射每条路线而无需单独执行每条路线?还是有其他更好的方法可以做到这一点,我错过了吗?

1 个答案:

答案 0 :(得分:0)

<Route component={subject.name} path={subject.path}>

不起作用,因为subject.name是一个字符串(如错误中指出的那样)。您需要路由对象指向实际组件而不是其名称才能使其工作。

<强> subjectRoutes.js

import Math from "../ui/subjectRoutes/routes/math"
import Science from "../ui/subjectRoutes/routes/science"

export const SubjectRoutes = [{
  name: Science,
  path: "/science"
},{
  name:Math,
  path:"/math"
}]

查看React Router的route configs,您可以在其中将数据映射到组件。