Last active
March 8, 2018 08:25
-
-
Save xiaoyunyang/2a00c2ac311f10f0e07e9ec3df0c8363 to your computer and use it in GitHub Desktop.
isomorphic-router-demo/iso-middleware/renderRoutes.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// iso-middleware/renderRoutes.js | |
import React from 'react'; | |
import { renderToString } from 'react-dom/server'; | |
import { StaticRouter } from 'react-router-dom'; | |
import { matchRoutes } from 'react-router-config'; | |
import routes from '../shared/routes'; | |
import HTML from '../shared/components/HTML'; | |
import App from '../shared/App'; | |
export default function renderRoute(req, res) { | |
const branch = matchRoutes(routes, req.url); | |
const promises = []; | |
branch.forEach(({ route, match }) => { | |
if (route.loadData) { | |
promises.push(route.loadData(match)); | |
} | |
}); | |
Promise.all(promises).then(data => { | |
// data will be an array[] of datas returned by each promises. | |
const context = data.reduce((context, data) => Object.assign(context, data), {}); | |
const router = <StaticRouter location={req.url} context={context}><App /></StaticRouter>; | |
const app = renderToString(router); | |
const html = renderToString(<HTML html={app} />); | |
return res.send(`<!DOCTYPE html>${html}`); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment