5

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

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.

当我使用 renderToString 函数注释掉该行时,我不再收到此错误(当然,该应用程序仍然无法运行 - 我只是不再收到错误消息)。

我试过传递 renderToString<RootApp />React.createElement(RoutingContext不是制造工厂,但这些都没有奏效。UsingReact.createElement导致了同样的错误,并且 using<RootApp />抛出了一个unexpected token < error.

以及对可能发生的事情的想法?

我的应用看起来像:

应用程序.js

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

应用程序.jsx

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

class App extends Component {

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

}

export default App;

索引.ejs

<!DOCTYPE html>
<html>
  <head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Vjeverica</title>

  </head>

  <body>
    <div id="root">
      <%- reactOutput %>
    </div>
    <script src="bundle.js"></script>

  </body>
</html>
4

1 回答 1

7

最终得到这个工作。问题在于我如何在 app.js 中要求 app.jsx - 因为我使用的是require而不是import,所以我需要更改require('./components/app.jsx')require('./components/app.jsx').default以获取默认导出。

于 2016-06-07T02:18:32.083 回答