Вкратце, вы будете:
Сохранить JSON в виде ZIP в Google Storage (сохранить память / пропускную способность / время)
Распакуйте файл в JSON (в RN)
Сохранить JSON в AsyncStorage (в RN)
Получить из AsyncStorage (в RN )
[Сводная информация о зависимостях] Вы можете сделать это, используя следующие депы:
Совет: Всегда сохраняйте большой язык json в формате zip (это может сэкономить до 90% размера).
Я сделал быстрый тест здесь: один 3.52 Файл MB json, получился заархивированный файл размером 26 КБ!
Давайте рассмотрим, что к вашему сохраненному zip-файлу можно получить доступ с помощью ссылки c publi, например: https://storage.googleapis.com/bucket/folder/lang-file.zip
.
Установите и свяжите все вышеперечисленные RPS, это необходимо для работы.
Импортируйте DPS
import RNFetchBlob from 'rn-fetch-blob';
import { unzip } from 'react-native-zip-archive';
import AsyncStorage from '@react-native-community/async-storage';
- Загрузите файл, используя
rn-fetch-blob
. Это можно сделать с помощью:
RNFetchBlob
.config({
// add this option that makes response data to be stored as a file,
// this is much more performant.
fileCache : true,
})
.fetch('GET', 'http://www.example.com/file/example.zip', {
//some headers ..
})
.then((res) => {
// the temp file path
console.log('The file saved to ', res.path())
// Unzip will be called here!
unzipDownloadFile(res.path(), (jsonFilePath) => {
// Let's store this json.
storeJSONtoAsyncStorage(jsonFilePath);
// Done!
// Now you can read the AsyncStorage everytime you need (using function bellow).
});
});
[функция] Распакуйте загруженный файл, используя
react-native-zip-archive
:
function unzipDownloadFile(target, cb) {
const targetPath = target;
const sourcePath = `${target}.json`;
const charset = 'UTF-8';
unzip(sourcePath, targetPath, charset)
.then((path) => {
console.log(`unzip completed at ${path}`)
return cb(path);
})
.catch((error) => {
console.error(error)
});
}
[функция] Store JSON в AsyncStorage:
function storeJSONtoAsyncStorage (path) {
RNFetchBlob.fs.readFile(path, 'utf-8')
.then((data) => {
AsyncStorage.setItem('myJSON', data);
});
}
Извлечение JSON данных из AsyncStorage (каждый раз, когда вы захотите):
AsyncStorage.getItem('myJSON', (err, json) => {
if (err) {
console.log(err);
} else {
const myJSON = JSON.parse(json);
// ... do what you need with you json lang file here...
}
})
Этого достаточно для получения динамических c json lang файлов, работающих в React Native.
Я использую этот подход, чтобы придать аналогичную особенность моему проекту i18n.