-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserverEntry.js
More file actions
65 lines (64 loc) · 2.53 KB
/
serverEntry.js
File metadata and controls
65 lines (64 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import fs from 'fs';
import React from 'react';
import fetch from 'isomorphic-fetch';
// import Hello from './Hello.js';
import ReactDOMServer from 'react-dom/server'
import { Provider } from 'react-redux'
import routes from './routes.js'
import * as promise from "es6-promise"
promise.polyfill()
import { match, createMemoryHistory, RouterContext } from 'react-router'
import configStore from './configStore'
function handleRender(req, res) {
//
// fs.readFile('./index.html', 'utf8', function (err, file) {
// res.send(file)
// })
const store = configStore({}, createMemoryHistory())
match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
if (error) {
res.status(500).send(error.message)
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search)
} else if (renderProps) {
let taskList = []
renderProps.components.forEach((component, idx) => {
component.fetchData && taskList.push(component.fetchData(store.dispatch))
})
// fetchData执行完毕后再进行渲染
Promise.all(taskList)
.then(()=>{
const reactString = ReactDOMServer.renderToString(
<Provider store={ store }>
<RouterContext {...renderProps}/>
</Provider>
)
fs.readFile('./index.html', 'utf8', function (err, file) {
const footString = '<script>(function(){window.__INITIAL_STATE__=' + JSON.stringify(store.getState()) + '})()</script>'
const document = file.replace(/<div id="app"><\/div>/, `<div id="app">${reactString}</div>${footString}`);
res.send(document)
})
})
} else {
res.status(404).send('Not found')
}
})
}
// function handleRender(req, res) {
// return fetch('http://localhost:3000/static/data.json')
// .then(r => r.json())
// .then(r => {
// const props = {name: 'NAME', hello: r.hello}
// const hello = React.createElement(Hello, props)
// fs.readFile('./index.html', 'utf8', function (err, file) {
// if (err) {
// return console.log(err);
// }
// const reactString = ReactDOMServer.renderToString(hello)
// const footString = '<script>(function(){window.__GLOBAL_STATE__=' + JSON.stringify(props) + '})()</script>'
// const document = file.replace(/<div id="app"><\/div>/, `<div id="app">${reactString}</div>${footString}`);
// res.send(document);
// });
// });
// }
export default handleRender;