【问题标题】:React server rendering --> Replacing React-rendered children with a new root componentReact 服务器渲染 --> 用新的根组件替换 React 渲染的子组件
【发布时间】:2024-01-12 23:44:01
【问题描述】:

我正在尝试渲染反应同构,它渲染但我在客户端收到警告/错误:

我使用 jspm 和 npm 作为包管理器;

warning.js:25 Warning: render(...): Replacing React-rendered children with a new root component. If you intended to update the children of this node, you should instead have the existing children update their state and render the new components instead of calling ReactDOM.render.

服务器renderToString输出的源:

<div id="reactRoot"><div data-reactroot="" data-reactid="1" data-react-checksum="845161664"><marquee data-reactid="2"><h1 data-reactid="3">App</h1></marquee></div></div>

render后react替换的source:

<div id="reactRoot"><div data-reactid=".0"><marquee data-reactid=".0.0"><h1 data-reactid=".0.0.0">App</h1></marquee></div></div>

快速服务器中间件:

import App from './components/App/App.jsx';
// [...] Express code removed for brevity
app.use('*', (req, res, next) => {
  try {
    res.render('index.html', {
      reactHtml: renderToString(
        <App />
      )
    });
  } catch (err) {
    next(err);
  }
});

index.html:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>App</title>
  <script>
    console.log('Running on <%- @env %> environment!');
    <% if (@env == 'development') : %>
    System.import('systemjs-hot-reloader/default-listener.js');
    <% end %>
    System.import('/app.jsx!')
    .catch(console.error.bind(console));
  </script>
</head>
<body>
  <div id="reactRoot"><%- reactHtml %></div>  
</body>
</html>

我在这里使用 ect 作为模板引擎;

app.jsx

import { render } from 'react-dom';
import App from './components/App/App.jsx';
const mountPoint = document.getElementById('reactRoot');
render(
  <App />,
  mountPoint
);

App/App.jsx:

import React from 'react';

const App = () => (
  <div>
    <marquee><h1>App</h1></marquee>
  </div>
);

export default App;

【问题讨论】:

  • 同样的问题,正在尝试解决
  • 对我来说,服务器和客户端的初始状态不同。我在堆栈中添加了很多东西,所以我无法准确找到导致错误的原因,但由于它没有停止我的应用程序,我能够继续。现在我有很多东西,如 react-router-component、redux、react-look...所以我不知道是什么解决了这个问题...稍后我将在这里发布一个要点和我的一些设置希望能有所帮助。

标签: javascript reactjs server-rendering


【解决方案1】:

使用 renderToStaticMarkup

// render the dynamic code of the page to a string.
var appHtml = React.renderToString(<Application/>);

// now use React as a static templating language to create the <html>, 
// <head>, and <body> tags
var fullPageHtml = React.renderToStaticMarkup(<HtmlPage content={appHtml}/>);

res.write(fullPageHtml); 

完整的问题解决讨论可以在这里找到。 https://github.com/aickin/react-dom-stream/issues/4

【讨论】:

    最近更新 更多