2017-06-03 143 views
2

我有一个应用程序,我在其中配置了服务器端渲染。一切正常,我的组件在服务器上呈现。问题是我在屏幕上渲染了两次组件。一个来自我用于服务器渲染的<div id="content"><%- content %></div>,另一个来自<script src="http://localhost:3001/bundle.js"></script>。我使用webpack为我的服务器和客户端创建两个捆绑包。为什么会发生这种情况,我该如何解决这个问题?使用服务器端渲染渲染两次React组件

视图/ index.ejs

<body> 
    <div id="app"></div> 
    <div id="content"><%- content %></div> 
    <script src="http://localhost:3001/bundle.js"></script> 
</body> 

index.js

app.use(Express.static(path.join(__dirname, '../', 'dist'))) 

app.use(serverRenderer) 
app.get('*', (req: Object, res: Object) => { 
    res.render('index', {content: req.body}) 
}) 

serverRender

import React from 'react' 
import ReactDOM from 'react-dom/server' 
import { match, RouterContext } from 'react-router' 
import routes from '../client/routes.js' 

async function render (component) { 
    const content = ReactDOM.renderToString(component) 
    return content 
} 

async function getMatchParams (routes, currentUrl) { 
    return new Promise((resolve, reject) => { 
    match({routes: routes, location: currentUrl}, (err, redirect, props) => { 
     if (err) { 
     return reject(err) 
     } 
     return resolve(props) 
    }) 
    }) 
} 

export default async(req, res, next) => { 
    const renderProps = await getMatchParams(routes, req.url) 
    if (renderProps) { 
    const component = (
     <RouterContext {...renderProps} /> 
    ) 
    req.body = await render(component) 
    next() 
    } 
} 

回答

0

确定。我发现了一个问题。我指的是捆绑和服务器呈现的字符串与两个单独的<div>。在我的app.js我这样做

render(
    <Router history={browserHistory}> 
     {routes} 
    </Router>, 
    document.getElementById('app') 
) 

这就是为什么我应该已经发送串这样的模板。

app.use(Express.static(path.join(__dirname, '../', 'dist'))) 

app.use(serverRenderer) 
app.get('*', (req: Object, res: Object) => { 
    res.render('index', {app: req.body}) 
}) 

最后我的意见/ index.js应该是这样的

<body> 
    <div id="app"><%- app %></div> 
    <script src="http://localhost:3001/bundle.js"></script> 
</body>