一个多语言的本机应用程序。每个语言包约为 50MB。将所有这些都包含在一个包中是没有意义的。那么,我该怎么办呢?
我认为正确的方法是在选择语言时下载相应的语言文件。接下来我该怎么办?我想使用 AsyncStorage 还是什么来存储它?
简要说明,您将:
将 JSON 以 ZIP 格式存储在 Google Storage 中(节省内存/带宽/时间)
将文件解压缩为 JSON(在 RN 中)
将 JSON 存储在 AsyncStorage 中(在 RN 中)
从 AsyncStorage 中检索(在 RN 中)
[依赖项摘要]您可以使用这些依赖项执行此操作:
提示:始终以 zip 格式存储大语言 json(这最多可以节省 90% 的大小)。
我在这里做了一个快速测试:一个 3.52MB 的 json 文件,结果是一个 26KB 的压缩文件!
让我们考虑一下您存储的 zip 文件,可以使用公共 url 访问,例如:https://storage.googleapis.com/bucket/folder/lang-file.zip。
安装并链接所有上述 RN deps,这是使其正常工作所必需的。
导入 deps
import RNFetchBlob from 'rn-fetch-blob';
import { unzip } from 'react-native-zip-archive';
import AsyncStorage from '@react-native-community/async-storage';
Run Code Online (Sandbox Code Playgroud)
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).
});
});
Run Code Online (Sandbox Code Playgroud)
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)
});
}
Run Code Online (Sandbox Code Playgroud)
function storeJSONtoAsyncStorage (path) {
RNFetchBlob.fs.readFile(path, 'utf-8')
.then((data) => {
AsyncStorage.setItem('myJSON', data);
});
}
Run Code Online (Sandbox Code Playgroud)
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...
}
})
Run Code Online (Sandbox Code Playgroud)
这足以让动态 json lang 文件在 React Native 中工作。
我正在使用这种方法为我的 i18n'ed 项目提供类似的功能。
| 归档时间: |
|
| 查看次数: |
569 次 |
| 最近记录: |