前言

上一篇已经使用 React template 创建好了应用,以及引入了 Reactrouter 。从本篇开始,就开始实现准备实现的功能了。 不用手动写路由,用循环来搞定。本篇的代码还是在上一章的 https://github.com/crazyhl/react-practise 代码中继续实现的。

下面是预计实现的功能

  • JSON格式化,查找
  • base64 decode/encode
  • md5
  • urlencode
  • unicode to 中文

今天一个都不实现,只是先把基础打好。

正文开始

先整理一波代码吧。之前的代码都在一个文件中。现在要把他们拆分开来,方便我们管理以及修改,互相不影响。最终代码结构如下。

增加了 router 目录,以及 pages 目录,将来还会增加 components 目录。

  • router 目录存放的是路由信息,由于不想把路由信息携带文件中,应该集中管理,所以提取出来了一个文件,不过这个路由信息目 前还比较简陋,仅仅满足当下的需要,后续,如果有更多的需求,在进行对应的改造。
  • pages 目录,存放的是页面的代码
  • 未来要增加的 components 目录,存放的则是小组件的代码,可以理解为页面中的代码段。

具体代码还是去 git 中看吧。我仅仅贴几个我觉得比较重要的部分

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// route.tsx
export type RouterMap = {
  path: string;
  name: string;
  component: string
}

export const RouterMaps = [
  {
    path:"/",
    name:"home",
    component: './home'
  },
  {
    path:"/topics",
    name:"topics",
    component: './topics'
  },
  {
    path:"/about" ,
    name:"about",
    component: './about'
  },
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// main-content.tsx
import { Switch, Route } from 'react-router-dom';
import "../App.css"
import { RouterMaps } from '../router/route';
import React, {Suspense} from 'react';

function MainContent() {
  const componentList = RouterMaps.map((com) => {
    const Component = React.lazy(() => import(`${com.component}`))

    return <Route exact key={com.name} path={com.path} render={() => (
        <Component />
    )}/>
  })
  return (
    <Suspense fallback={<div>Loading...</div>}>
    <Switch>
      {componentList}
    </Switch>
    </Suspense>
  )
}

export default MainContent

总结

原本啊 ,上周就能搞定的东西,是我在了解了皮毛之后就去开干,应该吧,文档中的各个属性看完才弄的,不过这样让我有了更多的理解,路由加载顺序,exact 的作用,lazyLoad。下一篇开始就是真正的功能实现了。