我在为反应应用设置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
App.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
有人可以指导我这里可能出现的问题吗?先谢谢。
答案 0 :(得分:1)
尝试更改
React.createElement(Layout, null, React.createElement(Routes))
到
React.createElement(Layout, null, React.createElement(Routes.default))
您可能在服务器端使用require
,而不是import
,这会导致一些差异。