关于react.js:react-动态加载路由

9次阅读

共计 2144 个字符,预计需要花费 6 分钟才能阅读完成。

前言

react-router4 不再举荐将所有路由规定放在同一个中央集中式路由,子路由应该由父组件动静配置,组件在哪里匹配就在哪里渲染,更加灵便

引入必要的依赖

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 的引入,这样天然就能够通过一个循环来实现动静的加载啦!

正文完
 0