我在为 React 应用程序设置 SSR 时遇到问题。渲染的服务器端代码如下:
app.use((req, res) => {
const context = {}
const body = ReactDOMServer.renderToString(
React.createElement(
Provider, { store },
React.createElement(
StaticRouter, { location: req.url, context: context },
React.createElement(Layout, null, React.createElement(Routes))
)
)
)
if (context.url) {
res.redirect(context.url)
} else {
res.status(200).send(template({ body }))
}
})
路由配置如下:Routes.js
const Routes = () => {
return (
<Switch>
<Route path="/" exact component={Home}/>
<Route path="*" component={NotFound}/>
</Switch>
)
}
export default Routes
应用程序.js
const App = () => {
return (
<Provider store={store}>
<BrowserRouter>
<Layout>
{router}
</Layout>
</BrowserRouter>
</Provider>
);
}
export default App
它抛出以下错误:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.
TypeError: element.type.toLowerCase is not a function
at ReactDOMServerRenderer.renderDOM (../node_modules/react-dom/cjs/react-dom-server.node.development.js:2304:28)
at ReactDOMServerRenderer.render (../node_modules/react-dom/cjs/react-dom-server.node.development.js:2298:21)
at ReactDOMServerRenderer.read (../node_modules/react-dom/cjs/react-dom-server.node.development.js:2234:19)
at Object.renderToString (../node_modules/react-dom/cjs/react-dom-server.node.development.js:2501:25)
at app.use (../server.js:59:33)
当我尝试打印 console.log(React.createElement(Routes));
时,它显示如下:
{ '$$typeof': Symbol(react.element),
type: [Function: Routes],
key: null,
ref: null,
props: {},
_owner: null,
_store: {} }
我已经使用 babel 从 Routes 文件创建了 CompiledRoutes 文件,并将其导入到 server.js 中,如下所示:
const Routes = require('./client/CRoutes').default
有人可以指导我这里可能是什么问题吗?在此先感谢。