加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React-Router 高级用法

发布时间:2020-12-15 06:36:08 所属栏目:百科 来源:网络整理
导读:使用对象而非 JSX 来配置路由 曾经的写法: Router Route path = "/" component = {App} IndexRoute component = {Dashboard} / Route path = "about" component = {About} / Route path = "inbox" component = {Inbox} Route path = "/messages/:id" compon

使用对象而非 JSX 来配置路由

曾经的写法:

<Router>
  <Route path="/" component={App}>
    <IndexRoute component={Dashboard} />
    <Route path="about" component={About} />
    <Route path="inbox" component={Inbox}>
      <Route path="/messages/:id" component={Message} />

      {/* 跳转 /inbox/messages/:id 到 /messages/:id */}
      <Redirect from="messages/:id" to="/messages/:id" />
    </Route>
  </Route>
</Router>

高级用法:

const routeConfig = [
  { path: '/',component: App,indexRoute: { component: Dashboard },childRoutes: [
      { path: 'about',component: About },{ path: 'inbox',component: Inbox,childRoutes: [
          { path: '/messages/:id',component: Message },{ path: 'messages/:id',onEnter: function (nextState,replaceState) {
              replaceState(null,'/messages/' + nextState.params.id)
            }
          }
        ]
      }
    ]
  }
]

React.render(<Router routes={routeConfig} />,document.body)

动态路由

Route 可以定义 getChildRoutes,getIndexRoute 和 getComponents 这几个函数。它们都是异步执行,并且只有在需要时才被调用。我们将这种方式称之为 “逐渐匹配”。 React Router 会逐渐的匹配 URL 并只加载该 URL 对应页面所需的路径配置和组件。

改写 routerConfig 时需要将 component 换成 getComponent。

const routeConfig = {
  path: '/',indexRoute: {
    getComponent(nextState,cb) {
      require.ensure([],(require) => { cb(null,require('components/layer/HomePage')) },'HomePage') },},getComponent(nextState,cb) { require.ensure([],require('components/Main')) },'Main') },childRoutes: [ require('./routes/baidu'),require('./routes/404'),require('./routes/redirect') ] }

getComponent 这个方法是异步的,也就是当路由匹配时,才会调用这个方法。

require.ensure 方法是 webpack 提供的方法,这也是按需加载的核心方法。第一个参数是依赖,第二个是回调函数。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读