【问题标题】:ES6 import and export modulesES6 导入导出模块
【发布时间】:2019-07-18 08:08:20
【问题描述】:

在另一个文件中我已经像这样导入但是当我在测试中使用时出现错误 React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for复合组件)但得到:未定义。您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。可以是什么?

import  { RateComponent,  mapStateToProps }   from '../components/Rate';
 it ('renders correctly if has data', () => {
    const tree = shallow( <RateComponent dispatch={jest.fn()}/>);
    expect(tree).toMatchSnapshot();
  });

这就是我的导出方式。

export 
{
  RateComponent,
  mapStateToProps
}
export default connect(mapStateToProps)(RateComponent);

【问题讨论】:

    标签: react-native es6-modules


    【解决方案1】:

    尝试导入默认导出,看看是否可行

    import RateComponent from '../components/Rate';
    

    你也不需要导出mapStateToProps

    【讨论】:

    • 谢谢!如果不需要导出,如何在测试 mapStateToProps 中使用?
    • 您已经在导入一个已连接的组件,该组件具有映射到道具的状态。
    【解决方案2】:

    正如 Clarity 已经指出的那样,只需从文件中导入 RateComponent。并通过 RateComponent 的一些道具,用于测试浅渲染组件和匹配 快照

    it ('renders correctly if has data', () => {
      const props = {
        // ...Define your props here with some values
      };
      const tree = shallow( <RateComponent {...props}/>);
      expect(tree).toMatchSnapshot();
    });
    

    【讨论】:

      猜你喜欢
      • 2017-06-29
      • 1970-01-01
      • 1970-01-01
      • 2017-01-04
      • 2018-12-09
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      • 2017-12-09
      相关资源
      最近更新 更多