4 React项目架构 - 目录划分 & Router配置

 

相关commit

0x0 目录划分

目录划分介绍

views文件夹

config文件夹

store文件夹

components

0x1 Router的简单实现

1 文件调整

/client/views/topic-list/index.jsx

import React from 'react'

export default class TopicList extends React.Component {
  componentDidMount() {
    //  placeholder
  }

  render() {
    return (
      <div>ㄟ...这里是to...topic li..li..list(。•́-ก̀。)</div>
    )
  }
}


/client/views/topic-detail/index.jsx

import React from 'react'

export default class TopicDetail extends React.Component {
  componentDidMount() {
    //  placeholder
  }

  render() {
    return (
      <div>喂喂喂,这里是topic detail!(o˘д˘)o有人在吗?</div>
    )
  }
}

2 配置路由

路由:区分一个网站不同功能模块的地址

前端路由:

react-router:


client/config/router.jsx

import React from 'react'
import {
  Route,

} from 'react-router-dom'

import TopicList from '../views/topic-list'
import TopicDetail from '../views/topic-detail'

export default () => [
  <Route path="/" component={TopicList} exact />,
  <Route path="/detail" component={TopicDetail} exact />,
]

说明:


client/views/App.jsx

import React from 'react'
import Routers from '../config/router'

export default class App extends React.Component {
  componentDidMount() {
    //  placeholder
  }

  render() {
    return [
      <div>初次见面,请多关照嘿嘿嘿~(๑^ں^๑)</div>,
      <Routers />,
    ]
  }
}

说明:

client/app.js

需要在整个app外面,包裹一层<BrowserRouter>,便于整体控制

...
import { BrowserRouter } from 'react-router-dom'
...
const render = (Component) => {
  ReactDOM.hydrate(
    <AppContainer>
      <BrowserRouter>
        <Component />
      </BrowserRouter>
    </AppContainer>, root,
  )
};
...


webpack.config.base.js

小调整:修改webpack的配置文件,让webpack在import没有后缀文件类型的js和jsx文件的时候,也能找到它们

resolve: {
  extensions: ['.js', '.jsx']
},


效果

3 使用Link做点击跳转

App.jsx

...
import { Link } from 'react-router-dom'
...
export default class App extends React.Component {
...
  render() {
    return [
      <div>
        <div>初次见面,请多关照嘿嘿嘿~(๑^ں^๑)</div>
        <Link to="/">⌲ 列表页</Link>
        <br />
        <Link to="/detail">⌲ 详情页</Link>
      </div>,
      <Routers />,
    ]
  }
}

效果

4 Redirect页面重定向

client/config/router.jsx

import React from 'react'
import {
  Route,
  Redirect,
} from 'react-router-dom'
...
export default () => [
  <Route path="/" render={() => <Redirect to="/list" />} exact />,
  <Route path="/list" component={TopicList} />,
  <Route path="/detail" component={TopicDetail} />,
]

说明: