javascript - 如何修复导入过程中的 'TypeError: undefined is not an object'

标签 javascript reactjs react-native

我正在尝试在 React Native 中组织我的通用 theme 文件夹。但在尝试默认导出不同文件中的模块时发现了问题。基本上,尝试做这个基本结构:

+-- components
+-- theme
|  +-- appStyles.js
|  +-- colors.js
|  +-- index.js

theme/appStyles.js中将导出默认的单个对象(与colors.js相同):

export default {
  screen: {
    flex: 1,
  },
};

theme/index.js中看起来像这样,它将导出默认的对象,映射主题文件夹中的文件:

import AppStyles from './appStyles';
import Colors from './colors';

export default {
  AppStyles,
  Colors,
};

当我尝试在另一个模块(即 SomeComponent.js)中使用它时,它只是未定义并且无法使用:

import { AppStyles } from '../theme';

console.log(AppStyles); // would log 'undefined'
<小时/>

作为一种解决方法,我一直在做:

theme/appStyles.js中:

export const AppStyles = {
  screen: {
    flex: 1,
  },
};

theme/index.js中:

export * from './appStyles';

然后它就可以在 SomeComponent.js 中使用:

import { AppStyles } from '../theme';

console.log(AppStyles); // would log Object structure
<小时/>

一直在 ReactJS Web 中使用这种“模式”。只是想知道 React Native 如何处理这个模块解析。

最佳答案

无需通过 {} 包装默认导出

import AppStyles from './appStyles';

export default AppStyles;

而不是简单地使用您想要的任何名称导入

import  AppStyles  from '../theme';

console.log(AppStyles);

我有多个内容要从索引导出

import  AppStyles  from '../theme';
import  Color from '../color';
export{
  Appstyle as default,
  Color
}

而不是简单地导入为

import  AppStyles, {Color}  from '../theme';

console.log(AppStyles);
console.log(Color);

关于javascript - 如何修复导入过程中的 'TypeError: undefined is not an object',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57753063/

相关文章:

javascript - 为什么嵌套的 ng-grid 高度不起作用?

javascript - AngularJS 在页面加载时加载数据

javascript - 为什么这个渲染测试的 react 组件失败了?

reactjs - 将图像添加到 React Bootstrap 下拉列表

react-native - react navigation v5 如何重置或更换?

javascript - 如何使用 AJAX 和 PHP 生成 .doc

javascript - 在 Yarn 2 (berry) 中审计依赖项的最佳方法是什么?

react-native - "react-native run-ios"时端口 8081 已在使用中

reactjs - 使用axios限速的建议

sockets - 用于响应 native 的socket.io(发送查询问题)