2016-07-14 20 views
1

你好我正在React Native中創建一個字典應用程序,我只是想存儲一個可以容納每個單詞定義的JSON blob數組。在React Native中存儲靜態和常用數據

我非常想避免硬編碼的數據,並希望我的代碼幹!

樣品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上的哪個庫用於關係數據庫。

謝謝你閱讀我的問題。

回答

1

你可以做你正在使用領域與下面的架構描述:

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並在啓動應用程序時初始化您的數據庫。

要創建/添加書籤:

// 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); 
}); 
+0

感謝阿里。我可以用普通的js腳本預先填充Realm文件嗎?例如,我需要一個JS文件中的Realm庫,一旦我運行它,它會輸出一個Realm文件嗎? –

+1

如果您在模擬器上運行,您可以在RN應用程序中預備文件,並輕鬆複製文件。您可以使用以下命令找出生成的領域文件的路徑:'console.log(realm.path)' – Ari

+0

哦,甜蜜!再次感謝! –

相關問題