如何在react中添加路由之实操篇

2017-06-17  本文已影响0人  cb12hx

首先,先来看看效果图

image.png

如上所示,点击About me ,到关于我的页面,点击Concact me,到联系我页面

再看看在服务端渲染的基础上改了什么东西

image.png

所有修改过的文件,新增的文件,一目了然,接下来一个个去看

1.app.js

//导入新包
import { RouterContext, match } from 'react-router'
//导入服务端客户端公用的路由文件
+import routes from './client/routes'
//修改render的方法,主要添加了match方法
function handleRender(req, res) {
  match({ routes: routes, location: req.url }, (err, redirectLocation, renderProps) => {
    if (err) {
      res.status(500).end(`server error: ${err}`)
    } else if (redirectLocation) {
      res.redirect(redirectLocation.pathname + redirectLocation.search)
    } else if (renderProps) {
      const helloChan = {
        config: {
          text: 'I come from serve side'
        }
      }
      const initialState = { helloChan }
      const store = configureStore(initialState);
      const html = renderToString(
        <Provider store={store}>
          <RouterContext {...renderProps}/>
        </Provider>
      )
      const finalState = store.getState();
      res.end(renderFullPage(html, finalState));
    } else {
      res.status(404).end('404 not found')
    }
  })
}

app.use('*', handleRender);

2.client/index.js

image.png

用图片吧,一目了然

3.containers/App.js

image.png

4.package.json

image.png

5.webpack.config.js

image.png

6.client/routes.js

import React from 'react'
import { Router,Route, IndexRoute } from 'react-router'
import About from '../containers/About'
import App from '../containers/App'
import Concact from '../containers/Concact'
import Index from '../containers/Index'

const routes = (
  <Route path="/" component={App} >
    <IndexRoute component={Index}/>
    <Route path="a" component={About} />
    <Route path="c" component={Concact} />
  </Route>
);

export default routes;

7.containers/About.js

import React, { Component } from 'react'

// @pureRender
export default class About extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div >
        My name is ben chan,I'm a web developer, I like js!
            </div>
    )
  }
}

8.containers/Concact.js

import React, { Component } from 'react'
// @pureRender
export default class About extends Component {
  constructor(props) {
    super(props);

    this.state = {};
  }
  render() {
    return (
      <div>
        <p>Phone:15895970807</p>
        <p>QQ:421416050</p>
        <p>Mail:15895970807@163.com</p>
            </div>
    )
  }
}

9.containers/Index.js

import React, { Component } from 'react'
import { Link } from 'react-router'
// @pureRender
export default class About extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <Link to='/a'>About me</Link>  <Link to='/c'>Concact me</Link>
      </div>
    )
  }
}

好了,由于篇幅,我们到下一篇再讲解到底做了什么

上一篇 下一篇

猜你喜欢

热点阅读