我有一个应用程序,我在其中配置了服务器端渲染。一切正常,我的组件在服务器上呈现。问题是我的组件在屏幕上呈现了两次。一个来自<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})
})
服务器渲染
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()
}
}