javascript - 在 React Native 中存储静态和公共(public)数据

标签 javascript json database react-native realm

你好,我正在 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"
  }
]

存储此数据的最佳策略是什么:

  1. 可以被用户加入书签
  2. 干净且易于更改并与其他文件分开
  3. 我的 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/

相关文章:

c++ - gltf 没有在皮肤中指定骨架值是什么意思?

javascript - angular 和 google analytics 集成 => ga 不是函数

javascript - jQuery 选择器,获取子元素少于 n 个的所有父元素

arrays - 通过 Graph API 将照片发布到 Facebook : OAuthException: (#100) param tags must be an array

javascript - 获取json ajax php表单进行远程工作

php - Foreach 循环运行一次查询

c# - 行计数

mysql - 外键和 WHERE 子句?

javascript - Firefox 扩展如何检测加载页面的内容类型?

javascript - 将固定侧边栏停止在页脚处 - 防止重叠