如何在react中添加路由之理论篇

在上一篇中,说明了修改的文件和新增的文件,这一篇将具体讲解做了什么
首先,调整了下文件的结构,把文件放到了src中

image.png

还记得我们改了什么文件了吗,提示大家一下,上面是修改的,下面的新增的

image.png

1.首先安装了react-router的依赖,注意此处要安装^2.8.1这个版本,我一开始安装的4,报了如下错,关于4.0,此处不涉及

TypeError: (0 , _reactRouter.match) is not a function

2.服务端,使用了match,具体如下
定义

match(location, cb)

这个函数被用于服务端渲染。它在渲染之前会匹配一组 route 到一个 location,并且在完成时调用 callback(error, redirectLocation, renderProps)

传给回调函数去 match的三个参数如下:
error:如果报错时会出现一个 Javascript 的 Error对象,否则是 undefined
redirectLocation:如果 route 重定向时会有一个 Location 对象,否则是 undefined
renderProps:当匹配到 route 时 props 应该通过路由的 context,否则是 undefined
如果这三个参数都是 undefined,这就意味着在给定的 location 中没有 route 被匹配到。

具体使用

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')
    }
  })
}

其中这一块,不知道大家有没有发现
没有路由前是这样的

 <Provider store={store}>
       <App />
 </Provider>

现在变成了这样

 <Provider store={store}>
     <RouterContext {...renderProps}/>
 </Provider>

RouterContext这个也是react-router中的功能块,它和match同时出现,其实简单来理解,就像下面说的
使用 match在渲染之前根据 location 匹配 route
使用 RoutingContext同步渲染 route 组件
3.客户端,也是导入了路由相关的代码,看具体变化

import { Router, browserHistory } from 'react-router'
import routes from './routes'

这一块截图比较最清楚


image.png

4.服务端客户端通用的路由文件,这个没什么好说的

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;

好了,其实主要就是加了这么多东西,这样看了下是不是很简单

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容