在单独的文件中声明React路由并导入

时间:2017-03-26 08:34:20

标签: javascript reactjs react-router

我是React的新手我一直试图在单独的文件中声明路由,然后在索引文件中使用它。 这是我的routes.js。

import React from 'react';
import ReactDOM from 'react-dom';
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom';
import App from './components/App';
import Template1 from './components/template1';
import Template2 from './components/template2';
import Template3 from './components/template3';

const routes = (
          <Route exact path="/" component={App}>
          <Route exact path="/sessionstate1" component={Template1}/>
          <Route exact path="/sessionstate2" component={Template2}/>
          <Route exact path="/sessionstate3" component={Template3}/>
    </Route>
)

export default routes

和index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {
  BrowserRouter as Router,
  Route,Redirect
} from 'react-router-dom';
import './styles/css/index.css';
import routes from './routes.js';

ReactDOM.render(
        <Router history={browserHistory} routes={routes} />,
        document.getElementById('root')
        );

我没有收到任何错误或警告,但页面未加载。请告诉我我错过了什么 感谢

8 个答案:

答案 0 :(得分:2)

我认为问题在于将Route包裹在div内。 尝试将它们包裹在Route内,如下所示。试试这个fiddle并将路由包装器更改为div。

const routes=(
      <Route >
        <Route exact path="/sessionstate1" component={Template1}/>
        <Route exact path="/sessionstate2" component={Template2}/>
        <Route exact path="/sessionstate3" component={Template3}/>
      </Route >
)
export default routes;

并将其导入index.js

import routes from './routes.js';

ReactDOM.render(
    <Router history={browserHistory} routes={routes} />,
    document.getElementById('root')
);

答案 1 :(得分:2)

您不需要将路径包裹在div中。尝试这样的事情:

routes.js

<?php
$query= $conn->query("SELECT * FROM schedule where day = Monday and stud_id = 8888") or die(mysql_error());
$time = strtotime(date('h:iA'));
$result = $query->fetchAll();
foreach($result as $row) {
    $timein = $row['timein'];
    $timeout = strtotime($row['timeout']);
    if ($time > $timeout)
    { 
        continue;
    } 
    else 
    {
        echo $timein;
    }
}

index.js

import React from 'react';
import { Router, Route } from 'react-router';
import { Template1, Template2, Template3 } from './templates';

const createRoutes = () => (
    <Router>
      <Route exact path="/sessionstate1" component={Template1}/>
      <Route exact path="/sessionstate2" component={Template2}/>
      <Route exact path="/sessionstate3" component={Template3}/>
    </Router>
);

export default createRoutes;

答案 2 :(得分:2)

index.js:

import LoginRoutes from './login/routes'

let routeConfig = [];
routeConfig = routeConfig.concat(LoginRoutes(store));

<Router routes={routeConfig}/>

routes.js:

export default (store) => {

    return [
        {path: '/login', component: Login},
        {path: '/signup', component: SignUp},
    ]
}

通过这种方式,您可以添加来自不同文件的路线,并将路线定义分散到不同的文件夹中,以满足路线的上下文目的。

如果您想使用redux并希望在路由上拥有onEnter事件,那么存储变量就在那里。例如:

export default () => {

    const sessionEnter = (location) => {
        let {appId} = location.params;

        store.dispatch(loadApp(appId));

    return [
        {path: '/apps/:appId', component: App, onEnter: sessionEnter},
    ]
}

我发现onEnter事件是componentDidMount的一个很好的替代方法,数据提取方式。在路由级别调用数据获取对我来说更有意义,因为我将组件视为表示级别的一部分。

答案 3 :(得分:1)

带有打字稿

将用于路由的文件分隔为route.ts

export const routes = [
    { path: '/', component: Home },
    { path: '/auth-callback', component: authCallback },
    { path: '/fetch-data/:startDateIndex?', component: FetchData }
];

在App.tsx中

export function App() {
    const routeComponents = routes.map(({ path, component }, key) => <Route exact path={path} component={component} key={key} />);
    return (
        <Layout>
            {routeComponents}
        </Layout>
    );
}

Layout.tsx

export default (props: { children?: React.ReactNode }) => (
    <React.Fragment>
        <div>
            <NavMenu />
            <TopAppBarFixedAdjust>
                {props.children}
            </TopAppBarFixedAdjust>
        </div>
    </React.Fragment>
);

答案 4 :(得分:1)

好几天前,我遇到了同样的问题,对我来说,解决方案是...

此路由文件之一:

import React from 'react';
import { Route } from 'react-router-dom';
import { ComponentY } from '../components/functionalitys';

export default [
  <Route path="/appointment" component={ComponentY} exact key="create" />,
];

这是另一个路由文件:

import React from 'react';
import { Route } from 'react-router-dom';
import { LoginPage, Register } from '../components/user';

export default [
  <Route path="/register" component={Register} exact key="create" />,
  <Route path="/login" component={LoginPage} exact strict key="login" />
];

这就是我导入主app.js的方式:

import routesFromFile1 from './the/route';
import routesFromFile2 from './the/other/route';

class App extends Component{
  render(){
    return(
       <div className="wrapper">
           <section className="content container-fluid">
              <Switch>  
                <Route exact path="/" component={Home} strict={true} exact={true}/>
                <Route path="/500" component={InternalServer} />
                {routesFromFile1}
                {routesFromFile2}
              </Switch>
            </section>
          </div>
        )
    }
}

希望对您有所帮助!干杯!

答案 5 :(得分:0)

像这样试试

import React from "react";
import {HashRouter as Router, Route} from 'react-router-dom';
import NoteContainer from "./component/note/index.jsx";
import Header from "./component/common/header.jsx";

const App = (props) => {
    return (
        <div className="container">
            <Header/> {props.children}
        </div>
    );
};

var x = () => {
    return (
        <h1>Hello world!</h1>
    );
};
module.exports = () => {
    return (
        <Router>
            <App>
                <Route path="/" component={NoteContainer}/>
                <Route path="/inbox" component={x}/>
            </App>
        </Router>
    );
};

答案 6 :(得分:0)

我知道我来晚了一点,但是我在这里工作 这里工作的demo

我的依赖项是

"react": "16.2.0",
"react-dom": "16.2.0",
"react-router-dom": "4.2.2",
"react-scripts": "1.1.0"

以此创建nav.js文件 该文件负责存储导航栏的所有链接

import React, { Component } from "react";
import { Link } from "react-router-dom";

class Navi extends Component {
  render = () => (
    <div>
      <Link to="/">Go to Home</Link> <br />
      <Link to="/about">Go to About</Link> <br />
      <Link to="/any-route">404 page</Link>
    </div>
  );
}

export default Navi;

然后是route.js文件 在这里,您将定义所有路线,以及路线应导航到的页面

import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
// your components
const Home = () => <h1>Home</h1>;
const About = () => <h1>About</h1>;
const MissingPage = () => <h1>404</h1>;

const routes = (
  <Switch>
    <Route path="/" exact component={Home} />
    <Route path="/about" component={About} />
    <Route component={MissingPage} />
  </Switch>
);

export default routes;

最后这是index.js的代码

import React, { Component } from "react";
import ReactDOM from "react-dom";

import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";

import Navi from "./nav";
import routes from "./routes";

// initialize rotues and navi links
const initRoutes = () => (
  <Router>
    <div>
      <Navi />
      {routes}
    </div>
  </Router>
);

const initializedRoutes = initRoutes();
ReactDOM.render(
  initializedRoutes, 
  document.getElementById("root")
);

答案 7 :(得分:-1)

也是新的反应并遇到了同样的问题。这是我尝试过的(显然不同的代码和结构,但我们正在寻找的应该是相同的功能)

index.js

import React from "react";
import ReactDOM from "react-dom";
import { createHashHistory } from "history";
import { BrowserRouter, Route } from 'react-router-dom';

import routes from "./routes";

const allRoutes = routes;

ReactDOM.render(
  allRoutes,
  document.getElementById("app")
)

和routes.js文件。

import React from "react";
import { createHashHistory } from "history";
import { BrowserRouter, Route } from 'react-router-dom';

import App from "./pages/App";
import Detail from "./pages/Detail";
import List from "./pages/List";

const routes =  (
  <BrowserRouter>
    <div>
        <Route exact path="/" component={ App } />
        <Route path="/" component={ List } />
        <Route path="/detail/:repo" component={ Detail } />
    </div>
  </BrowserRouter>
);

export default routes;

请告诉我这是否适合您。