[英]How to fix 'TypeError: undefined is not an object' during import
I'm trying to organize my common theme
folder in React Native. 我正在尝试在React Native中组织我的通用theme
文件夹。 But found a problem when trying to default export a module in a different file. 但是在尝试默认将模块导出到其他文件中时发现了一个问题。 Basically, trying to do this basic structure: 基本上,尝试执行以下基本结构:
+-- components
+-- theme
| +-- appStyles.js
| +-- colors.js
| +-- index.js
In theme/appStyles.js
would export default a single object (same for colors.js
): 在theme/appStyles.js
将默认导出一个对象(与colors.js
相同):
export default {
screen: {
flex: 1,
},
};
In theme/index.js
looks like this where it'll export default an object, mapping the files in the theme folder: 在theme/index.js
,它看起来像这样,它将默认导出一个对象,映射主题文件夹中的文件:
import AppStyles from './appStyles';
import Colors from './colors';
export default {
AppStyles,
Colors,
};
When I'm trying to use this in another module, ie SomeComponent.js
, it would just be undefined and would be unusable: 当我尝试在另一个模块(即SomeComponent.js
)中使用它时,它将只是未定义且将无法使用:
import { AppStyles } from '../theme';
console.log(AppStyles); // would log 'undefined'
As a work around, I've been doing: 作为解决方案,我一直在做:
In theme/appStyles.js
: 在theme/appStyles.js
:
export const AppStyles = {
screen: {
flex: 1,
},
};
In theme/index.js
: 在theme/index.js
:
export * from './appStyles';
It would then be usable in SomeComponent.js
: 这样就可以在SomeComponent.js
:
import { AppStyles } from '../theme';
console.log(AppStyles); // would log Object structure
Been using this 'pattern' in ReactJS Web. 在ReactJS Web中一直在使用这个“模式”。 Just wondering how does React Native handle this module resolution. 只是想知道React Native如何处理此模块分辨率。
No need to wrap default export by {}
无需使用{}
包装默认导出
import AppStyles from './appStyles';
export default AppStyles;
Than simply import with whatever name you want 只需导入任何您想要的名称即可
import AppStyles from '../theme';
console.log(AppStyles);
I have multiple things to be exported from index 我有很多东西要从索引中导出
import AppStyles from '../theme';
import Color from '../color';
export{
Appstyle as default,
Color
}
Than simply import as 比简单地导入为
import AppStyles, {Color} from '../theme';
console.log(AppStyles);
console.log(Color);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.