您好,我正在react native中创建一个字典应用程序,我只想存储一个json blob数组,其中包含每个单词的定义。
我非常想避免硬编码的数据,希望我的代码是干的!
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]});
您可以使用所有字典条目预先填充领域文件,并将其与应用程序捆绑在一起,或者您也可以下载此文件或json并在启动应用程序时初始化db。
创建/添加书签:
// 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);
});