温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

React中怎么动态加载路由

发布时间:2021-06-17 15:23:32 来源:亿速云 阅读:819 作者:Leah 栏目:web开发

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>

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI