首页 > 解决方案 > 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/)

我想我遇到了一些逻辑问题(语法看起来不错),所以如果我遗漏了什么或有任何其他解决方案,谢谢你的建议!

编辑:添加了我的文件夹结构。

文件夹结构

标签: javascriptreactjsreact-native

解决方案


好的,我想我找到了你的问题。在 Translations.js 中,您的导出语句应该是

export default Translations;

代替

export default Translations();

还要确保所有类别文件都以相同的方式导出。看看这是否有效。


推荐阅读