【发布时间】:2017-06-13 09:21:42
【问题描述】:
我正在使用 create-react-app 开发一个应用程序,并且我正在尝试将我的代码拆分为实现 react-router huge-apps 示例中描述的方式的模块。 除了单元测试之外,一切都运行良好:我在运行路由组件的开玩笑测试时遇到此错误:
TypeError: Cannot read property 'contextTypes' of undefined
路由组件如下所示:
export class IntroPage extends React.Component {
render() {
return (
<div></div>
);
}
}
const mapStateToProps = (state) => {
return {
...
}
};
module.exports = connect(mapStateToProps)(IntroPage);
还有一个测试:
import React from 'react';
import {shallow} from 'enzyme';
import {IntroPage} from '../IntroPage';
it('should render without crashing', () => {
shallow(
<IntroPage {...props}/> // IntroPage is undefined
)
});
我必须如何导出/导入我的组件才能正确测试它们。
谢谢。
【问题讨论】:
-
为什么在一个文件中同时使用 ES6 导出语法和 CommonJS module.exports?这不受支持。
-
CommonJS 语法支持兼容性,但你不应该在任何新代码中使用它。将它们混合在语义上是错误的,因为它们具有相互冲突的含义。
-
我知道,但是如果我像在 es6 中那样导出组件(导出默认值),它就不起作用了。
-
我不得不说我的路由定义是这样的:export default { childRoutes: [ { path: '/', component: require('./components/app/App') }, { path : '*', onEnter: (nextState, replace) => replace('/') } ] };
-
这是 react-router 示例中暴露的方式。
标签: reactjs webpack react-router react-redux