gpt4 book ai didi

reactjs - 使用服务器端渲染对 React 组件进行两次渲染

转载 作者:行者123 更新时间:2023-12-03 14:28:16 24 4
gpt4 key购买 nike

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

最佳答案

好的。我发现了一个问题。我指的是带有两个单独的 <div> 的 bundle 和服务器渲染字符串。 。在我的 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>

关于reactjs - 使用服务器端渲染对 React 组件进行两次渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44349500/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com