React Router - 来自单独文件的路由

时间:2018-03-18 14:37:23

标签: javascript reactjs

我正在构建小型SPA网络应用程序,具有反应,反应路由器和语义。当我决定将我的路线从主.jsx移动到单独的文件时出现问题。我想创建类似于this的东西,理论上一切都运行良好,但路线中的组件未定义'。

我的项目结构如下:

root
 |_ src
     |_ config
     |   |_ routes.js
     |   | ...
     |_ app
         |_ index.jsx
         | ...

routes.js:

import { Main, Add } from 'views';

export const routes = [
  {
    component: Main,
    path: '/',
  }, {
    component: Add,
    path: '/add',
  },
];

Index.jsx:

import React from 'react';
import ReactDOM from 'react-dom';

import { routes } from 'config';
import {
  BrowserRouter,
  Route,
  Switch,
} from 'react-router-dom';

export class Index extends React.Component {
  render() {
    return (
      <BrowserRouter>
        <Switch>
          {routes.map(props => <Route {...props} />)}
        </Switch>
      </BrowserRouter>
    );
  }
}

ReactDOM.render(<Index />, document.getElementById('app'));

当我将console.log(routes)放入渲染器时,我得到了类似的东西:

[
  { component: undefined, path: "/" },
  { component: undefined, path: "/add" }
]

我不知道问题出在哪里。

2 个答案:

答案 0 :(得分:0)

您在routes.js文件中导入的组件需要指定一个类似import { Main, Add } from 'path/to/views'; export const routes = [ { component: Main, path: '/', }, { component: Add, path: '/add', }, ]; 的路径

git reset --hard

答案 1 :(得分:0)

App.tsx

import routes from "./routes";
const App: React.FC = () => {
  return (
      <BrowserRouter>
        <div>
          <Switch>
            {routes.data.map((entry) => {return (<Route {...entry}/>)})}
          </Switch>
        </div>
      </BrowserRouter>
  );
};

export default App;

router.ts

const routes = {data: [
        {
            key: "one",
            path: "/three"

        },
        {
            key: "two",
            path: "/two"
        }
    ]
}

export default routes;