React二之搭建基本页面及配置路由
我们基于react模板项目做调整,搭建项目的基本页面及外层路由。
步骤
1、配置基本页面
项目根目录下新建views目录,在views目录下新建admin(可当做后台页面目录)、home(可当做前台页面目录)文件夹,分别新建index.js文件
admin\index.js
function Admin() {
return (
<div>后台首页</div>
);
}
export default Admin;
home\index.js
function Home() {
return (
<div>首页</div>
);
}
export default Home;
在views目录下新建index.js(在文件里导出页面)
import Loadable from 'react-loadable';
import Loading from '../components/loading';
//需要将对外的普通组件需要进行懒加载
const Home = Loadable({
loader: () => import('./home'),
loading: Loading,
});
const Admin = Loadable({
loader: () => import('./admin'),
loading: Loading,
});
export {
Home,
Admin
}
说明:采用路由懒加载(项目根目录下执行yarn add react-loadable);新建src/components/loading/index.js文件(当懒加载未完成时,会显示该页面的内容)
src/components/loading/index.js
function loading() {
return (
<div>加载中...</div>
);
}
export default loading;
2、配置路由(项目根目录下执行yarn add react-router-dom)
在src文件下新建routes文件夹,在其下新建index.js文件并配置路由
import {
Home,
Admin
} from "../views"; // 引入页面
export const mainRoute = [
{
pathname:"/home",
component: Home
}
];
export const admainRoute = [
{
pathname: "/admin/home",
component: Admin,
exact: true
}
];
3、最外层去渲染路由视图(修改src目录下的index.js)
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { HashRouter as Router, Route, Redirect, Switch } from 'react-router-dom';
import { mainRoute } from './routes';
ReactDOM.render(
<Router>
<Switch>
<Route path="/admin" component={App}/>
{
mainRoute.map( (route, key)=>{
return <Route path={route.pathname} component={route.component} key={key}/>
})
}
<Redirect to='/home' from='/' exact/>
</Switch>
</Router>,
document.getElementById('root')
);
reportWebVitals();
4、配置内层App路由(在src/App.js文件里渲染路由视图)
import React, { Component } from 'react';
import { admainRoute } from './routes';
import {Route,Redirect,Switch} from 'react-router-dom';
export default class App extends Component {
render() {
return (
<Switch>
{
admainRoute.map((route, key)=>{
return <Route path={route.pathname} component={route.component} exact={route.exact} key={key}/>
})
}
<Redirect to={admainRoute[0].pathname} from='/admin' exact/>
</Switch>
)
}
};
5、启动项目(项目根目录下执行yarn start)
6、浏览器访问
主页面验证(访问:http://localhost:3000)
admin模块主页面验证(访问:http://localhost:3000/#/admin)
项目目录
github源码:https://github.com/smallgrey/react-advanced/tree/basic_pages_and_routes
码云地址:https://gitee.com/smallgrey/react-advanced/tree/basic_pages_and_routes
上一篇: JavaScript 事件
推荐阅读