gpt4 book ai didi

node.js - "Invariant Violation"在服务器端使用 React Server renderToString

转载 作者:搜寻专家 更新时间:2023-10-31 22:41:56 26 4
gpt4 key购买 nike

我正在尝试使用 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而不是 build 工厂,但这些都没有奏效。使用 React.createElement导致相同的错误,并使用 <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>

最佳答案

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

关于node.js - "Invariant Violation"在服务器端使用 React Server renderToString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37625136/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com