在上一篇中金麸,說明了修改的文件和新增的文件挥下,這一篇將具體講解做了什么
首先桨醋,調(diào)整了下文件的結(jié)構(gòu),把文件放到了src中
還記得我們改了什么文件了嗎喜最,提示大家一下瞬内,上面是修改的,下面的新增的
1.首先安裝了react-router的依賴章咧,注意此處要安裝^2.8.1這個版本能真,我一開始安裝的4,報(bào)了如下錯疼约,關(guān)于4.0,此處不涉及
TypeError: (0 , _reactRouter.match) is not a function
2.服務(wù)端程剥,使用了match,具體如下
定義
match(location, cb)
這個函數(shù)被用于服務(wù)端渲染织鲸。它在渲染之前會匹配一組 route 到一個 location,并且在完成時調(diào)用 callback(error, redirectLocation, renderProps)
昙沦。
傳給回調(diào)函數(shù)去 match的三個參數(shù)如下:
error:如果報(bào)錯時會出現(xiàn)一個 Javascript 的 Error對象盾饮,否則是 undefined
redirectLocation:如果 route 重定向時會有一個 Location 對象丘损,否則是 undefined
renderProps:當(dāng)匹配到 route 時 props 應(yīng)該通過路由的 context,否則是 undefined
如果這三個參數(shù)都是 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')
}
})
}
其中這一塊而钞,不知道大家有沒有發(fā)現(xiàn)
沒有路由前是這樣的
<Provider store={store}>
<App />
</Provider>
現(xiàn)在變成了這樣
<Provider store={store}>
<RouterContext {...renderProps}/>
</Provider>
RouterContext這個也是react-router中的功能塊臼节,它和match同時出現(xiàn),其實(shí)簡單來理解巨税,就像下面說的
使用 match在渲染之前根據(jù) location 匹配 route
使用 RoutingContext同步渲染 route 組件
3.客戶端草添,也是導(dǎo)入了路由相關(guān)的代碼维费,看具體變化
import { Router, browserHistory } from 'react-router'
import routes from './routes'
這一塊截圖比較最清楚
4.服務(wù)端客戶端通用的路由文件,這個沒什么好說的
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;
好了,其實(shí)主要就是加了這么多東西阅畴,這樣看了下是不是很簡單