动态

详情 返回 返回

react 動態加載路由 - 动态 详情

前言

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 的引入,這樣自然就可以通過一個循環來實現動態的加載啦!

user avatar tianmiaogongzuoshi_5ca47d59bef41 头像 haoqidewukong 头像 smalike 头像 freeman_tian 头像 qingzhan 头像 kobe_fans_zxc 头像 razyliang 头像 leexiaohui1997 头像 inslog 头像 zero_dev 头像 solvep 头像 woniuseo 头像
点赞 65 用户, 点赞了这篇动态!
点赞

Add a new 评论

Some HTML is okay.