Javascript 在单独的文件中声明 React 路由并导入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43026690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Declaring React Routes in a separate file and Importing
提问by Vipin
I am new to React I have been trying to declare routes in separate files and then use it in index file. Here is my routes.js.
我是 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
and index.js
和 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')
);
I am not getting any errors or warning but the page is not loading. Please tell me what i am missing Thanks
我没有收到任何错误或警告,但页面没有加载。请告诉我我缺少什么谢谢
回答by Edvinas daugirdas
You don't need to wrap your Routes inside a div. Try something like this:
您不需要将 Routes 包装在 div 中。尝试这样的事情:
routes.js
路由.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;
index.js
索引.js
import ReactDOM from 'react-dom';
import createRoutes from './routes';
const routes = createRoutes();
ReactDOM.render(
routes,
document.getElementById('root')
);
回答by Guy
index.js:
索引.js:
import LoginRoutes from './login/routes'
let routeConfig = [];
routeConfig = routeConfig.concat(LoginRoutes(store));
<Router routes={routeConfig}/>
routes.js:
路线.js:
export default (store) => {
return [
{path: '/login', component: Login},
{path: '/signup', component: SignUp},
]
}
This way you can add routes from different files and spread your route definitions to different folders that serve the contextual purpose of the route.
通过这种方式,您可以添加来自不同文件的路线,并将您的路线定义传播到为路线提供上下文目的的不同文件夹。
The store variable is there in case you want to use redux and want to have an onEnter event on the route. Example:
如果您想使用 redux 并希望在路线上有一个 onEnter 事件,那么 store 变量就在那里。例子:
export default () => {
const sessionEnter = (location) => {
let {appId} = location.params;
store.dispatch(loadApp(appId));
return [
{path: '/apps/:appId', component: App, onEnter: sessionEnter},
]
}
I find onEnter events a good alternative to componentDidMount, data-fetching-wise. Invoking a data fetch on route level makes more sense to me as I see the component as part of the presentation level.
我发现 onEnter 事件是 componentDidMount 的一个很好的替代方案,在数据获取方面。在路由级别调用数据获取对我来说更有意义,因为我将组件视为表示级别的一部分。
回答by DroidNoob
I think the problem is with wrapping the Routeinside a div.
Try wrapping them inside a Routelike following. Try this fiddleand change the routes wrapper to div.
我认为这个问题是包裹Route内div。尝试将它们包装在Route如下类似的内容中。试试这个小提琴并将路由包装器更改为 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;
And import it into index.js
并将其导入 index.js
import routes from './routes.js';
ReactDOM.render(
<Router history={browserHistory} routes={routes} />,
document.getElementById('root')
);
回答by San Jaisy
With Typescript
使用打字稿
Sepate the file for routes as routes.ts
将路由文件分离为 routes.ts
export const routes = [
{ path: '/', component: Home },
{ path: '/auth-callback', component: authCallback },
{ path: '/fetch-data/:startDateIndex?', component: FetchData }
];
In the App.tsx
在 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
布局.tsx
export default (props: { children?: React.ReactNode }) => (
<React.Fragment>
<div>
<NavMenu />
<TopAppBarFixedAdjust>
{props.children}
</TopAppBarFixedAdjust>
</div>
</React.Fragment>
);
回答by NuOne
I know I'm little late but here my working here a working demo
我知道我有点晚了,但我在这里工作是一个工作演示
my dependencies are
我的依赖是
"react": "16.2.0", "react-dom": "16.2.0", "react-router-dom": "4.2.2", "react-scripts": "1.1.0"
"react": "16.2.0", "react-dom": "16.2.0", "react-router-dom": "4.2.2", "react-scripts": "1.1.0"
create nav.js file as this this file is responsible for storing all the links for navbar
创建 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;
Then the routes.js file here you will define all your routes, and your pages where the routes should navigates to
然后,这里的 routes.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;
finally here is the code for index.js
最后这里是 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")
);
回答by error404
Try it like this way
像这样试试
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>
);
};
回答by mcshakes
Also new to react and was running into the same issue. Here is what I tried (obviously different code and structure, but what we're looking for should be the same functionality)
也是新手反应并且遇到了同样的问题。这是我尝试过的(显然不同的代码和结构,但我们正在寻找的应该是相同的功能)
index.js
索引.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")
)
and the routes.js file.
和 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;
Let me know if that works for you.
让我知道这是否适合您。

