Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了node.js – 在服务器端使用React Server renderToString的“不变冲突”大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用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而不是制作工厂,并且这些都没有工作.使用React.createElement导致相同的错误,并使用< RootApp />抛出一个意外的令牌<错误. 关于可能发生的事情的想法? 我的应用看起来像: app.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;
}

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;

index.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>

解决方法

@H_616_28@ 结束了这个工作.问题在于我如何在app.js中要求app.jsx – 因为我使用require而不是import,我需要将require(‘./ components / app.jsx’)更改为require(‘./ components / app.jsx’).获取认导出.

大佬总结

以上是大佬教程为你收集整理的node.js – 在服务器端使用React Server renderToString的“不变冲突”全部内容,希望文章能够帮你解决node.js – 在服务器端使用React Server renderToString的“不变冲突”所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。