![](/img/trans.png)
[英]How to fix “Element type is invalid: expected a string … but got: object” error in React
[英]got “Element type is invalid: expected a string” when trying to server side rendering react
我收到此錯誤:
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
嘗試使用ReactDOMServer.renderToStaticMarkup
。
這是我的應用程序:
"use strict";
import React from 'react'
module.exports = () => {
return (
<div></div>
);
};
這是我的節點服務器渲染代碼:
"use strict";
const path = require('path');
const webpack = require('webpack');
const React = require('react'), ReactDOMServer = require('react-dom/server'),
DOM = React.DOM, body = DOM.body, div = DOM.div, script = DOM.script;
webpack({
target: "node",
entry: [
path.resolve(__dirname, '../js', 'app.js'),
],
module: {
loaders: [
{
exclude: /node_modules/,
loader: 'babel',
test: /\.js$/,
},
]
},
output: {filename: 'app.bundle.js', path: __dirname},
},() => {
const App = React.createFactory(require('./app.bundle.js'));
let html = ReactDOMServer.renderToStaticMarkup(body(null,
div({
id: 'root', dangerouslySetInnerHTML: {
__html: ReactDOMServer.renderToString(App())
}
})
));
});
有誰知道導致此錯誤的原因以及如何解決此問題?
提前致謝。
似乎該捆綁包默認情況下與commonjs不兼容。 正如我在webpack docs中閱讀的那樣 ,您需要在輸出對象中添加libraryTarget:'commonjs2'
才能做到這一點。
像這樣:
output: {filename: 'app.bundle.js', path: __dirname,libraryTarget:'commonjs2'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.