使用服务器端呈现

时间:2017-06-03 23:40:47

标签: reactjs server-rendering

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

视图/ 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()
  }
}

2 个答案:

答案 0 :(得分: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})
})

最后我的 views / index.js 看起来应该是这样的

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

答案 1 :(得分:0)

我也遇到了这个问题并找到了解决方案。

在package.json上,

"start": "npm-run-all --parallel dev:*",

它将运行webpack和node build / bundle.js。 然后两件事同时发生:webpack build projectnode build/bundle.js

在webpack构建项目之后,由于bundle.js更改,因此node build/bundle.js再次运行。

因此,服务器端和客户端都进行了两次呼叫。我很轻松地解决了这个问题。

首先运行npm run build,然后运行node build/bunde.js。然后它将运行所有内容一次:)

相关问题