require() 不适用于变量 - 反应原生 [英] require() not working with variable - react native

查看:65
本文介绍了require() 不适用于变量 - 反应原生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个奇怪的问题.如果我设置一个变量 direclty,其值类似于const myString = 'someWord';"那行得通,但如果我从这样的变量const myString = someVariable;"中获取值,那将不起作用,并且如果我将值设置在也不起作用的条件块上.

I meet a weird problem. If I set a variable direclty with a value like this "const myString = 'someWord';" that work but if I take the value from a variable like this "const myString = someVariable;", that doesn't work, and if I set the value on a conditional block that doesn't work too.

所以,工作:

    var jsonName = 'tramwayen';
    const pathex = require('../assets/JSON/' + jsonName);
    var json = JSON.parse(JSON.stringify(pathex));

不起作用:

    var jsonName = variable;
    const pathex = require('../assets/JSON/' + jsonName);
    var json = JSON.parse(JSON.stringify(pathex));

不起作用:

    var jsonName = '';
    if (condition) {
       jsonName = 'tramwayen';
    }
    const pathex = require('../assets/JSON/' + jsonName);
    var json = JSON.parse(JSON.stringify(pathex));

我真的不明白.

我有这个错误:第 41 行的调用无效:require('../assets/JSON/' + jsonName2)"

I have this error : "Invalid call at line 41: require('../assets/JSON/' + jsonName2)"

推荐答案

大多数 JS 打包器无法处理动态 require 导入.您可能希望加载所有文件,并将它们放入一个对象中:

Most JS bundlers cannot handle dynamic require imports. You might want to load all of the files, and put them in an object:

let data = {
    tramwayen: require('../assets/JSON/tramwayen.json'),
    something: require('../assets/JSON/something.json'),
    // and so on
};

并使用 data 对象检索您需要的数据.

And use the data object to retrieve the data you need.

这篇关于require() 不适用于变量 - 反应原生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆