简体   繁体   English

React 中将 json 导入变量的问题

[英]Problem with import json to variable in React

I'm new in React and I'm trying to import and save in variable a selected JSON data我是 React 的新手,我正在尝试导入并保存一个选定的 JSON 数据变量

 [...] const languageToSet = "polish"; const lang = { promiseToSetLanguage: function(lang){ return new Promise((resolve, reject) => { import language from `./languages/${languageToSet}_lang.json` language = JSON.parse(language) if (language.welcome) { console.log('Works fine') resolve(true) } else{ reject(false) } }) } } lang.promiseToSetLanguage() [...]

Console throw me a error: "'import' and 'export' may only appear at the top level" but i need to load a JSON file selected by user.控制台向我抛出一个错误:“'import' 和 'export' 可能只出现在顶层”,但我需要加载用户选择的 JSON 文件。 I used 'import' and 'require' method.我使用了“导入”和“要求”方法。

Thanks for your help, best regards.感谢您的帮助,最好的问候。

I think that fetch might be the answer here.. Try to use我认为 fetch 可能是这里的答案.. 尝试使用

return new Promise(async (resolve, reject) => {
            const rawJsonFile = await fetch(`${file_from_user}`);
            const jsonFile = await rawJsonFile.json();
            if (jsonFile.welcome) {
                console.log('Works fine')
                resolve(true)
            } else{
                reject(false)
            }
        })

If it still wont work, you can always use xhr如果它仍然不起作用,您可以随时使用 xhr

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

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