简体   繁体   English

如何通过 React 在资源(.json、.csv 等)上使用代码拆分

[英]How to use code splitting on a ressouce (.json, .csv, etc.) with React

Issue:问题:

I am using react-intl and I would like to load the language-related JSON file only when it is needed, in brief to lazy load it .我正在使用react-intl ,我想仅在需要时才加载与语言相关的JSON 文件,简而言之就是延迟加载它

Documentation:文档:

https://reactjs.org/docs/code-splitting.html the problem here is I wish to lazy load a JSON file not a component, so I am a bit lost about how to use it without JSX. https://reactjs.org/docs/code-splitting.html这里的问题是我想延迟加载一个 JSON 文件而不是一个组件,所以我有点丢失了关于如何在没有 JSX 的情况下使用它的问题。

Actual code:实际代码:

import React from 'react';
import {IntlProvider} from 'react-intl';
import English from "../i18n/en.json";
import Polish from "../i18n/pl.json";

const local = navigator.language;
let lang;
switch (local){
    case "pl":
    case "pl-pl":
        lang = Polish;
        break;
    default:
        lang = English;
}

function Wrapper () {
[...]
}

export default Wrapper

What I try which did not works:我尝试的方法不起作用

test 1:测试1:

import React from 'react';
import {IntlProvider} from 'react-intl';
const English = React.lazy(() => import('../i18n/en.json'));
const Polish = React.lazy(() => import('../i18n/pl.json'));

const local = navigator.language;
let lang;
switch (local){
    case "pl":
    case "pl-pl":
        lang = Polish;
        break;
    default:
        lang = English;
}

function Wrapper () {
[...]
}

export default Wrapper

test 2:测试2:

import React from 'react';
import {IntlProvider} from 'react-intl';
const English = React.lazy(() => import('../i18n/en.json'));
const Polish = React.lazy(() => import('../i18n/pl.json'));

const local = navigator.language;
let lang;
switch (local){
    case "pl":
    case "pl-pl":
        Polish.then(polish => {lang = polish});
        break;
    default:
        English.then(english=> {lang = english});
}

function Wrapper () {
[...]
}

export default Wrapper

test 3 (inspired from How to import Json file with React lazy loading? ):测试 3(灵感来自如何使用 React 延迟加载导入 Json 文件? ):

import React from 'react';
import {IntlProvider} from 'react-intl';

const local = navigator.language;
let lang;
switch (local){
    case "pl":
    case "pl-pl":
        import("../i18n/pl.json").then(Polish=> {
            lang = Polish);
        });
        break;
    default:
        import("../i18n/en.json").then(English=> {
            lang = English);
        });
}

function Wrapper () {
[...]
}

export default Wrapper

In case more code is needed (the function Wrapper for example), please let me know in a comment:)如果需要更多代码(例如 function Wrapper),请在评论中告诉我:)

I also had the same issue where I wanted to code split my JSON in React.我也有同样的问题,我想在 React 中对 JSON 进行代码拆分。 I found a work around that uses the dynamic import function.我找到了一个使用动态导入 function 的解决方法。

I wasn't using Intl so I can't confirm this works for your needs but this is what worked for my needs (and I think it should work for you)我没有使用 Intl,所以我无法确认这是否适合您的需求,但这符合我的需求(我认为它应该适合您)

I created a function to return a promise with my data that I needed to code split.我创建了一个 function 来返回一个 promise,其中包含我需要进行代码拆分的数据。 I then called this in my Component in an Async func with an await on the data.然后我在我的组件中调用了这个,在一个异步函数中等待数据。

My use case was to fetch data from an API, if that was done, load a cached JSON of the data.我的用例是从 API 获取数据,如果这样做了,则加载数据的缓存 JSON。

const loadCached = (key) => {
  return new Promise((res, rej) => {
    import(`../datasets/cached/${key}.json`).then((data) => {
      res(data?.default);
    });
  });
};

I then called it from my async catch然后我从我的async catch中调用它

const cachedData = await loadCached(key);

So for you use I would keep my loadCached function (maybe rename it to like loadLang )因此,对于您使用,我会保留我的loadCached function (也许将其重命名为loadLang

then wrap it in a useEffect to fire on load to change the language and gather the JSON.然后将其包装在useEffect中以在加载时触发以更改语言并收集 JSON。

Here is how I would approach your issue (untested code)这是我将如何处理您的问题(未经测试的代码)

const local = navigator.language; // get language
const [lang, setLang] = useState("English"); // for a default of english

// fire when we get local from DOM
useEffect(() => {
  async function getLangData() {
    const response = await loadLang(local);
    setLang(reponse);
  }
getLangData();
}, [local])


const setLang = (lang) => {
  return new Promise((res, rej) => {
    import(`../i18n/${lang}.json`).then((data) => {
      res(data?.default);
    });
  });
};

暂无
暂无

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

相关问题 使用.json,.csv等 D3中的文件 - Using .json,.csv,etc. files in D3 使用circe以递归方式将JSON树转换为其他格式(XML,CSV等) - Transform JSON tree to other format (XML, CSV etc.) recursively with circe 如何使用简单的查询将 JSON 文件导入 MySQL 数据库,而不实际将其转换为任何其他文件格式,如 CSV 等? - How can I import a JSON file into MySQL database, using a simple query, without actually converting it to any other file formats like CSV etc.? 将 JSON 转换为 CSV - 字符串操作(jq、bash、awk、sed 等) - Convert JSON to CSV - string manipulation (jq, bash, awk, sed, etc.) API 返回包含换行符等的 json。我该如何清理我的 json? - API returns json containing linebreaks etc. how can i clean my json? 在空手道DSL中,如何将替换文本用于其他数据类型,例如int,float,Big等? - In Karate DSL, how can I use the replace text for other data types such as int, float, Big, etc.? 如何使用$ http从不带扩展名的链接(如.json等)中检索AngularJS中的数据? - How to retrieve data in AngularJS using $http from a link without a extension (like .json, etc.)? 如何查询解析 json object 子值是否包含/等于/大于等? - How to query on parse json object child value if it contains/equal to/greater than etc.? 如何在Scala / Play中将JSON转换为简单的旧数据(Map,List,String,Int等) - How do I turn JSON into plain old data (Map, List, String, Int etc.) in Scala/Play 提供JSON / XML / etc的Web服务。 回复 - Web service that serve JSON/XML/etc. responses
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM