简体   繁体   English

在本机中动态要求json文件(来自数千个文件)

[英]Require json file dynamically in react-native (from thousands of files)

I googled so far and tried to find out the solution but not yet. 到目前为止,我用谷歌搜索并试图找出解决方案,但还没有。

I know require() works only with static path, so I want alternative ways to solve my problem. 我知道require()仅适用于静态路径,因此我需要其他方法来解决我的问题。 I found this answer here but it doesnt make sense for thousands of resources. 我在这里找到了这个答案但是对于成千上万的资源却没有意义。

Please advise me the best approach to handle such case. 请告诉我处理这种情况的最佳方法。

Background 背景

I have thousand of json files that containing app data, and declared all the file path dynamically like below: 我有数千个包含应用程序数据的json文件,并动态声明了所有文件路径,如下所示:

export var SRC_PATH = {
    bible_version_inv: {
        "kjv-ot": "data/bibles/Bible_KJV_OT_%s.txt",
        "kjv-nt": "data/bibles/Bible_KJV_NT_%s.txt",
        "lct-ot": "data/bibles/Bible_LCT_OT_%s.txt",
        "lct-nt": "data/bibles/Bible_LCT_NT_%s.txt",
        "leb": "data/bibles/leb_%s.txt",
        "net": "data/bibles/net_%s.txt",
        "bhs": "data/bibles/bhs_%s.txt",
        "n1904": "data/bibles/na_%s.txt",
        .....
        "esv": "data/bibles/esv_%s.txt",
        .....
    },
    ....

As you can see, file path contains '%s' and that should be replace with right string depends on what the user selected. 如您所见,文件路径包含'%s',应将其替换为正确的字符串取决于用户选择的内容。

For example if user select the bible (abbreviation: "kjv-ot") and the chapter 1 then the file named "data/bibles/Bible_KJV_OT_01.txt" should be imported. 例如,如果用户选择圣经(缩写:“ kjv-ot”)和第1章,则应导入名为“ data / bibles / Bible_KJV_OT_01.txt”的文件。

I'm not good enough in react-native, just wondering if there is other alternative way to handle those thousands of resource files and require only one at a time by dynamically following the user's selection. 我在本机响应方面还不够好,只是想知道是否还有其他替代方法可以处理这数千个资源文件,并且可以通过动态遵循用户的选择来一次只需要一个

Any suggestions please. 有任何建议请。

Instead of exporting a flat file, you could export a function that took a parameter which would help build out the paths like this: 除了导出平面文件,您还可以导出带有参数的函数,该参数将帮助构建如下路径:

// fileInclude.js
export const generateSourcePath = (sub) => {
     return {
         bible_version_inv: {
            "kjv-ot": `data/bibles/Bible_KJV_OT_${sub}.txt`
         }
     }
}


//usingFile.js
const generation = require('./fileInclude.js');
const myFile = generation.generateSourcePath('mySub');

const requiredFile = require(myFile);

then you would import (or require) this item into your project, execute generateSourcePath('mysub') to get all your paths. 那么您可以将该项目导入(或要求)到您的项目中,执行generateSourcePath('mysub')以获取所有路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM