【问题标题】:React Router - routes from separate fileReact Router - 来自单独文件的路由
【发布时间】:2018-08-27 04:39:42
【问题描述】:

我正在构建带有反应、反应路由器和语义的小型 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',
  },
];

索引.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" }
]

我不知道问题出在哪里。

【问题讨论】:

  • “视图”是否在另一个文件夹中?

标签: javascript reactjs


【解决方案1】:

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;

路由器.ts

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

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

export default routes;

【讨论】:

    【解决方案2】:

    在 routes.js 文件中导入的组件需要指定一个路径,例如 import { Main, Add } from '../views';

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

    【讨论】:

    • 我已经在 webpack 中设置了 Views 的路径,所以路径不会引起问题,因为我在其他地方使用了这种方法,并且效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2020-07-04
    • 2016-10-27
    • 1970-01-01
    • 2020-01-03
    相关资源
    最近更新 更多