我对reactjs很新,并且正在使用react-router v4 测试基本的服务器端渲染,但我无法理解这个错误,一直在尝试。我尝试过在谷歌上找到的所有解决方案,但似乎都没有。
这是server.js代码:
import Express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router'
import MyRoutes from './routes/routes.js';
...
app.get('*', (req, res) => {
let markup = `<!DOCTYPE html>
<html lang="en">
<body>
${renderToString(<StaticRouter location={req.url} context={{}}><MyRoutes/></StaticRouter>)}
</body>
</html>`;
res.write(markup);
res.end();
});
问题似乎与以下代码有关:
./ routes / routes.js代码:
import React from 'react';
import { Match, Miss } from 'react-router';
const componentTest = () =>
(
<div>
Testing a component
</div>
);
export default () => (
<div>
<Match exactly={true} pattern="/" component={componentTest} />
</div>
);
现在如果我删除了匹配标记行,则会显示空白页面而没有错误。 但如果匹配标记行在那里,我会收到以下错误:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.
in Unknown
in Router (created by StaticRouter)
in StaticRouter
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of `StatelessComponent`.
at invariant (/home/ubuntu/workspace/node_modules/react-dom/node_modules/fbjs/lib/invariant.js:44:15)
at instantiateReactComponent (/home/ubuntu/workspace/node_modules/react-dom/lib/instantiateReactComponent.js:74:56)
at instantiateChild (/home/ubuntu/workspace/node_modules/react-dom/lib/ReactChildReconciler.js:44:28)
at /home/ubuntu/workspace/node_modules/react-dom/lib/ReactChildReconciler.js:71:16
at traverseAllChildrenImpl (/home/ubuntu/workspace/node_modules/react-dom/lib/traverseAllChildren.js:77:5)
at traverseAllChildren (/home/ubuntu/workspace/node_modules/react-dom/lib/traverseAllChildren.js:172:10)
at Object.ReactChildReconciler.instantiateChildren (/home/ubuntu/workspace/node_modules/react-dom/lib/ReactChildReconciler.js:70:7)
at ReactDOMComponent.ReactMultiChild.Mixin._reconcilerInstantiateChildren (/home/ubuntu/workspace/node_modules/react-dom/lib/ReactMultiChild.js:187:41)
at ReactDOMComponent.ReactMultiChild.Mixin.mountChildren (/home/ubuntu/workspace/node_modules/react-dom/lib/ReactMultiChild.js:226:27)
at ReactDOMComponent.Mixin._createContentMarkup (/home/ubuntu/workspace/node_modules/react-dom/lib/ReactDOMComponent.js:653:32)
非常感谢任何帮助。
答案 0 :(得分:1)
Tharaka Wijebandara在评论中给出了解决方法。
问题是Match
已被Route
中的react-router v4
取代。因此,用此行替换Match
标记行解决了它:
<Route exact path="/" component={componentTest} />