【问题标题】:React - Mapping out Components returning errorReact - 映射出返回错误的组件
【发布时间】:2017-08-20 23:24:34
【问题描述】:

我想构建一个包含许多页面的应用程序,我认为最好的方法是将所有页面名称和路径放入一个单独的文件中,然后将每个页面映射出来,而不是长渲染中的组件列表。我唯一的问题是,当我尝试使用 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"
}]

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

【问题讨论】:

    标签: reactjs meteor react-router-dom


    【解决方案1】:
    <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,您可以在其中将数据映射到组件。

    【讨论】:

      猜你喜欢
      • 2017-06-20
      • 1970-01-01
      • 2014-10-29
      • 1970-01-01
      • 2021-10-12
      • 2020-05-16
      • 2014-11-20
      • 2016-08-12
      • 1970-01-01
      相关资源
      最近更新 更多