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

首先,先来看看效果图

如何在react中添加路由之实操篇_第1张图片
image.png

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

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

如何在react中添加路由之实操篇_第2张图片
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(
        
          
        
      )
      const finalState = store.getState();
      res.end(renderFullPage(html, finalState));
    } else {
      res.status(404).end('404 not found')
    }
  })
}

app.use('*', handleRender);

2.client/index.js

如何在react中添加路由之实操篇_第3张图片
image.png

用图片吧,一目了然

3.containers/App.js

如何在react中添加路由之实操篇_第4张图片
image.png

4.package.json

如何在react中添加路由之实操篇_第5张图片
image.png

5.webpack.config.js

如何在react中添加路由之实操篇_第6张图片
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 = (
  
    
    
    
  
);

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 (
      
My name is ben chan,I'm a web developer, I like js!
) } }

8.containers/Concact.js

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

    this.state = {};
  }
  render() {
    return (
      

Phone:15895970807

QQ:421416050

Mail:[email protected]

) } }

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 (
      
About me Concact me
) } }

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

你可能感兴趣的:(如何在react中添加路由之实操篇)