在 React Native 中存储静态和公共数据

Storing static and common data in React Native

本文关键字:静态 公共数据 存储 React Native      更新时间:2023-09-26

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

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

  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);
});