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()
}
}