"不变违规"在服务器端使用React Server renderToString

时间:2016-06-04 00:16:53

标签: node.js reactjs isomorphic-javascript serverside-rendering

我尝试使用Webpack设置同构服务器端渲染React应用程序,但是当我尝试使用renderToString将我的React代码转换为字符串时出现此错误:

www.example.com,www.domain.com,www.anotherdomain.com

当我使用renderToString函数注释掉该行时,我停止收到此错误(当然,应用程序仍然无法正常工作 - 我不再收到错误消息)。

我尝试过传递renderToString Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. <RootApp />而不是制作工厂,但这些都没有奏效。使用React.createElement(RoutingContext导致了同样的错误,并使用React.createElement投了<RootApp />

关于可能发生的事情的想法?

我的应用看起来像:

app.js

unexpected token < error

app.jsx

"use strict"

require("babel-register");
const Express = require('express');
const BodyParser = require('body-parser');
const Path = require('path');
const Fs = require('fs');
const Url = require('url');
const ReactRouter = require('react-router');
const React = require('react');
const ReactDOMServer = require('react-dom/server');

const app = Express();
app.set('view engine', 'ejs');

app.get('*', (req, res) => {
  let RootApp = require('./components/app.jsx');
  let rootAppFactory = React.createFactory(RootApp);
  let reactHtml = ReactDOMServer.renderToString(rootAppFactory({}));
  res.render('index', {reactOutput: reactHtml});
})

if (process.env.NODE_ENV !== 'test') {
  let port = process.env.port || 4000;
  app.listen(port);
  console.log('Listening on port', port);
} else {
  module.exports = app;
}

index.ejs

import React, {Component} from 'react';
import ReactDOM from 'react-dom';

class App extends Component {

  render() {
    return (
      <div>
        {this.props.children}
      </div>
    )
  }

}

export default App;

1 个答案:

答案 0 :(得分:5)

结束了这项工作。问题在于我如何在app.js中要求app.jsx - 因为我使用的是require而不是import,我需要将require('./components/app.jsx')更改为require('./components/app.jsx').default获取默认导出。