你好,我正在 React Native 中创建一个字典应用程序,我只是想存储一个 JSON blob 数组来保存每个单词的定义。
我非常希望避免对数据进行硬编码并希望我的代码是 DRY!
示例 JSON blob:
[
{
"word": "triangle",
"definition": "a plane figure with three straight sides and three angles.",
"type": "noun"
},
{
"word": "square",
"definition": "a plane figure with four equal straight sides and four right angles.",
"type": "noun"
},
{
"word": "circle",
"definition": "a round plane figure whose boundary (the circumference) consists of points equidistant from a fixed point (the center).",
"type": "noun"
}
]
存储此数据的最佳策略是什么:
- 可以被用户加入书签
- 干净且易于更改并与其他文件分开
- 我的 React 组件如何访问它
我认为关系数据库是最好的方法,但我很难弄清楚如何将数据植入数据库。以及将 React Native 上的哪个库用于关系数据库。
感谢您阅读我的问题。
最佳答案
您可以使用具有以下架构的 Realm 来执行您所描述的操作:
let EntrySchema = {
name: 'Entry',
primaryKey: 'word',
properties: {
word: 'string',
definition: 'string',
type: 'string'
}
};
let BookmarkListsSchema = {
name: 'BookmarkList',
properties: {
bookmarks: {type: 'list', objectType: 'Entry'}
}
};
let realm = new Realm({schema: [EntrySchema, BookmarkListsSchema]});
您可以使用所有字典条目预填充一个 Realm 文件并将其与您的应用程序捆绑在一起,或者您可以下载此文件或 JSON 并在启动应用程序时初始化您的数据库。
创建/添加书签:
// create your list once
var bookmarkList;
realm.write(() => {
bookmarkList = realm.create('BookmarkList');
});
// add entry for 'triange' to bookmarks
realm.write(() => {
let triangeEntry = realm.objectForPrimaryKey('Entry', 'triangle');
bookmarkList.bookmarks.push(triangleEntry);
});
关于javascript - 在 React Native 中存储静态和公共(public)数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38385772/