媒介
置信很多人都遇到过想在React项目中动态加载路由这类题目,接下来我们逐渐完成。
引入必要的依靠
import React from 'react'
import { Router, Route, IndexRoute, hashHistory } from 'react-router'
接下来建立一个component函数
目标就是为了变成router的component完成异步加载。
// 异步按需加载component
function asyncComponent(getComponent) {
return class AsyncComponent extends React.Component {
static Component = null;
state = { Component: AsyncComponent.Component };
componentDidMount() {
if (!this.state.Component) {
getComponent().then(({default: Component}) => {
AsyncComponent.Component = Component
this.setState({ Component })
})
}
}
//组件将被卸载
componentWillUnmount(){
//重写组件的setState要领,直接返回空
this.setState = (state,callback)=>{
return;
};
}
render() {
const { Component } = this.state
if (Component) {
return <Component {...this.props} />
}
return null
}
}
}
在此申明componentWillUnmount钩子是为了处理Can only update a mounted or mounting component的这个题目,原因是当脱离页面今后,组件已被卸载,实行setState时没法找到衬着组件。
接下来完成当地文件途径的传入
function load(component) {
return import(`./routes/${component}`)
}
将已知地点途径通报到一个函数并把这个函数作为参数通报到 asyncComponent中如许asyncComponent就能够接收到这个路由的地点了,然后我们要做的就是将这个asyncComponent函数带入到router中。
<Router history={hashHistory}>
<Route name="home" breadcrumbName="首页" path="/" component={MainLayout}>
<IndexRoute name="undefined" breadcrumbName="未定义" component={() => <div>未定义</div>}/>
<Route name="Development" breadcrumbName="施工中" path="Development" component={DevelopmentPage}/>
<Route breadcrumbName="个人助理" path="CustomerWorkTodo" component={({children}) => <div className="box">{children}</div>}>
<Route name="Agency" breadcrumbName="待办事项" path="Agency" component={asyncComponent(() => load('GlobalNotification/CustomerWorkAssistantTodo/CustomerAgencyMatter'))}/>
<Route name="Already" breadcrumbName="已办事项" path="Already" component={asyncComponent(() => load('GlobalNotification/CustomerWorkAssistantTodo/CustomerAlreadyMatter'))}/>
<Route name="SystemMessage" breadcrumbName="体系音讯" path="SystemMessage/:data" component={asyncComponent(() => load('GlobalNotification/SystemMessage/SystemMessage'))}/>
<Route name="SystemMessagePer" breadcrumbName="体系音讯概况" path="SystemMessagePer/:data" component={asyncComponent(() => load('GlobalNotification/SystemMessage/SystemMessagePer'))}/>
</Route>
</Router>
</Router>
从代码中能够看出已完成了router 的component 的引入,如许天然就能够够经由过程一个轮回来完成动态的加载啦!