javascript - React Native - 基于switch case循环导出对象
问题描述
我是 React Native 的新手,我正在努力解决对象导出问题。在我的应用程序中,我从存储在变量中的后端简单字符串接收Settings.translationType
。收到后,我正在渲染一个简单的视图,让我们这样说:
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import Translations from '../constants/Translations';
export default class HomeScreen extends Component {
render() {
return(
<View>
<Text>{Translations.one}</Text>
</View>
)
}
}
还有一些麻烦。我有一个 .js 文件(翻译),这取决于来自后端服务的内容,它提供了正确的翻译类别名称。它看起来像这样:
import Category1 from './translations/Category1';
import Category2 from './translations/Category2';
import Category3 from './translations/Category3';
const Translations = () => {
switch (Settings.translationType) {
case '2':
return Category2;
case '3':
return Category3;
default:
return Category1;
}
}
export default Translations();
在./translations
文件夹中,我有三个 .js 文件,如下所示:
import LocalizedStrings from 'localized-strings';
const Category1 = new LocalizedStrings({
en: {
one: 'Restaurant',
two: 'Café',
three: 'Pub'
},
fi: {
one: 'Ravintola',
two: 'Kahvila',
three: 'Pub'
},
sw: {
one: 'Restaurang',
two: 'Kafé',
three: 'Pub'
},
de: {
one: 'Restaurant',
two: 'Cafe',
three: 'Pub'
},
})
export default Category1;
在 Expo CLI 中运行我的应用程序后,Settings.translationType
总是从 BE 正确获取,但我遇到如下错误:Unable to resolve module './translations/Category1.js' from '~/RN/MyProject/src/constants/Translations.js': The module './translations/Category1.js' could not be found from '~RN/MyProject/src/constants/Translations.js'. Indeed, non of these files exists: (and there are listed the files with other extensions of Category1 file, located at ~/RN/MyProject/src/constants/translations/)
我想我遇到了一些逻辑问题(语法看起来不错),所以如果我遗漏了什么或有任何其他解决方案,谢谢你的建议!
编辑:添加了我的文件夹结构。
解决方案
好的,我想我找到了你的问题。在 Translations.js 中,您的导出语句应该是
export default Translations;
代替
export default Translations();
还要确保所有类别文件都以相同的方式导出。看看这是否有效。
推荐阅读
- php - 测试 http Laravel
- python - 如何解决通过正则表达式获取字符串的“将字符串转换为浮点数时出错”?
- sql - Where...IN 条件中的 SQL 多个 ID 列
- labview - 我需要帮助更改连接到伺服电机的 LabVIEW 读取 VI 的数据采集速率
- list - Flutter 可以创建 AnimationController 列表吗?
- excel - 获取范围内最后一个非空单元格的列号(如果值不唯一)
- javascript - Next.js/React - 如何从 Apollo 客户端 HOC 普遍解析用户语言?
- security - 如何为您不信任的特定 vscode 扩展禁用 Internet 访问
- visual-studio-code - VSCode Rest客户端 - 如何将变量设置为变量
- xpages - XPages 百分比字段