当我从另一个js文件访问js文件的const值时,我得到未定义的数据
Abc.js
import { Platform } from 'react-native';
const abc = Platform.select({
ios: [
'com.abc',
'com.xyz'
],
android: [
'com.pqr',
'com.lmn'
]
});
export default abc
App.js
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
Button,
View
} from 'react-native';
import { abc } from "./Abc";
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' +
'Cmd+D or shake for dev menu',
android: 'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
onPressgetData = () => {
console.warn("DATA " + JSON.stringify(abc));
}
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
!! Welcome to React Native !!
</Text>
<Button title="get Data"
color="#841584"
onPress={() => onPressgetData()} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
当我点击获取数据而不是数组时,我从我的App.js访问abc const数据我在警告中未定义。我不知道我错在哪里谢谢你提前
答案 0 :(得分:5)
您已将模块导出为default
并将其导入为named import
,因此未定义。
更改
import { abc } from "./Abc";
到
import abc from "./Abc";
获得正确的结果
答案 1 :(得分:1)
从文件导出单个组件时,您可以使用export default abc
,这可以通过import abc from './abc'
当您的文件包含许多组件/功能时,您必须使用export functionName
单独导出每个功能并使用
import { functionName, functionName2, functionName3 } from './abc'
您还可以使用导出默认的SpecialFunctionName以及其他导出。 所以,当你
import SpecialFunctionName(can use any name here) from './abc'
你将永远获得SpecialFunctionName,因为它是efault export