反应服务器渲染 - >用新的根组件

时间:2016-04-15 17:38:00

标签: javascript reactjs server-rendering

我尝试渲染反应同构,然后渲染但我在客户端发出警告/错误说:

我使用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>

在渲染后用反应替换了源:

<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;

1 个答案:

答案 0 :(得分: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