javascript 复杂异步反应路由器v4示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 复杂异步反应路由器v4示例相关的知识,希望对你有一定的参考价值。

import React, { PureComponent } from 'react'
import { Match, Miss, Redirect } from 'react-router'

const isAsyncCapable = typeof window !== 'undefined'
export default class Routes extends PureComponent {
  constructor() {
    super()

    this.views = {}

    this.redirs = [{
      pattern: '/redirect',
      to: '/',
    }, {
      pattern: '**/',
      to: ({ location }) => location.pathname.slice(0, -1),
      exactly: true,
    }].map(redir => {
      const { to } = redir
      return {
        ...redir,
        to: typeof to !== 'function' ? () => to : to
      }
    })

    this.routes = [{
      name: 'home',
      pattern: '/',
      exactly: true,
    }, {
      name: 'about',
      pattern: '/about',
    }, {
      name: '404',
    }].map(route => ({
      ...route,
      component: this.loadView.bind(this, route.name),
    }))
  }

  loadView(fileName) {
    return isAsyncCapable ? this.asyncLoader(fileName) : this.syncLoader(fileName)
  }

  syncLoader(fileName) {
    const View = require(`./views/${fileName}`)
    return <View />
  }

  asyncLoader(fileName) {
    const storedView = this.views[fileName]
    if (storedView) {
      delete this.views[fileName]
      return storedView
    }

    new Promise(resolve => require.ensure([], require => {
      resolve(require(`./views/${fileName}`).default)
    }))
    .then(View => this.views[fileName] = <View />)
    .then(() => this.forceUpdate())
    .catch(err => {
      console.error(err)
      throw new Error(err)
    })

    return <div />
  }

  renderRedirs() {
    return this.redirs.map(redir => this.renderRedir(redir))
  }

  renderRedir({ pattern, exactly, to }) {
    return <Match
      key={pattern}
      pattern={pattern}
      exactly={exactly}
      render={props => <Redirect to={to(props)} />}
    />
  }

  renderRoutes() {
    return this.routes.map(route => this.renderRoute(route))
  }

  renderRoute({ name, pattern, exactly, component }) {
    if (pattern) {
      return <Match
        key={name}
        pattern={pattern}
        exactly={exactly}
        component={component}
      />
    } else {
      return <Miss
        key={name}
        component={component}
      />
    }
  }

  render() { return (
    <div>
      {this.renderRoutes()}
      {this.renderRedirs()}
    </div>
  )}
}

以上是关于javascript 复杂异步反应路由器v4示例的主要内容,如果未能解决你的问题,请参考以下文章

javascript 反应页面转换(假设反应路由器v4)

反应路由器 v4 默认页面(未找到页面)

javascript 异步反应路由器组件加载

用开玩笑酶测试反应路由器 v4

使用 redux 保护的路由和身份验证反应路由器 v4

以编程方式反应路由器 v4 导航