webpack
从零搭建一个空的React
项目,现在接下来开始完善这个架子,增加按需加载的功能和多级路由的功能,关于redux的功能将在下次开始添加。React
官方提供的lazy
方法,这个lazy
有个坑,就是必须要结合Suspense
来使用,单独使用会直接报错。import React, { Suspense, lazy } from ‘react‘;
/**
* 通用的按需加载组件的方法
* 使用如下
* const HelloWorld = AsyncComponent(() => import(‘Components/test/HelloWorld‘));
*/
const AsyncComponent = (importFunc) => {
const Component = lazy(importFunc);
return (props) => (
<Suspense
fallback={<div>loading...</div>}
>
<Component {...props} />
</Suspense>
)
}
react-router
升级到4.0以后就不再支持Route
的多级嵌套了,所以每次存在子路由的时候,可能需要一个公共的父级页面来专门渲染子路由。routes
文件夹下添加对应的路由配置文件。import { AsyncComponent } from ‘Utils/component‘;
const Main = AsyncComponent(() => import(‘Pages/main‘));
const Home = AsyncComponent(() => import(‘Pages/Home‘));
const HelloWorld = AsyncComponent(() => import(‘Components/test/HelloWorld‘));
const routes = [
{
path: ‘/‘,
component: Main,
exact: true // 严格匹配,保证刚进来的时候直接展示首页
},
{
path: ‘/‘,
component: Home, // 模糊匹配,进入子路由的时候,就会走这里
children: [
{
path: ‘/hello‘,
component: HelloWorld
}
]
}
];
export default routes;
/**
* 路由遍历功能
*/
const renderRoutes = (routes) => {
return routes.map((route, index) => {
const { children, path, exact = false } = route;
/**
* 可以在这里做一些全局的处理,把search参数处理之后传进route.component,这样就不用每个页面都要对search参数去做一次处理
*/
const search = location.search;
const query = searchToQuery(search); // 将search字符串变成一个对象,然后传入
return (
<Route
path={path}
exact={exact}
key={`${route.path}-${index}`}
render={props => <route.component {...props} routes={children} urlQuery={query} />}
/>
)
})
}
index.js
中使用路由。import React from "react";
import ReactDOM from "react-dom";
import { Router } from ‘react-router‘;
import { createBrowserHistory } from ‘history‘;
import { renderRoutes } from ‘Utils/component‘;
import routes from ‘Routes‘;
const browserHistory = createBrowserHistory();
// 使用browserHistory有一个注意点,本地开发时,需要将webpack的config.devServer.historyApiFallback设置为true。不然会出现你输入路径时,把路径当做接口来访问,而不是当做路由。
function render() {
ReactDOM.render(
<Router history={browserHistory}>
{
renderRoutes(routes)
}
</Router>,
document.getElementById("root")
);
}
render();
从零开始,构建自己的react项目(二)增加多级路由和按需加载组件
原文:https://www.cnblogs.com/aloneMing/p/13032528.html