React组件使用服务器端渲染呈现两次

3
我有一个应用程序,在其中配置了服务器端渲染。一切都很顺利,我的组件在服务器端呈现。问题是我在屏幕上看到了两次呈现的组件。一个来自于我用于服务器渲染的 <div id="content"><%- content %></div>,另一个来自于 <script src="http://localhost:3001/bundle.js"></script>。我使用webpack为我的服务器和客户端制作了两个包。这是怎么回事,我该如何解决?

views/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})
})

服务器端渲染

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个回答

1

好的。我找到了一个问题。我在我的app.js中使用两个单独的<div>引用bundle和服务器渲染的字符串。

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>

0

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

在 package.json 文件中,

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

它将运行webpack和node build/bundle.js。 然后同时发生了两件事情,webpack构建项目node build/bundle.js

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

因此,在服务器和客户端上都调用了两次。我很容易地解决了这个问题。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接