自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

在React應(yīng)用中使用Dexie.js進(jìn)行離線數(shù)據(jù)存儲

開發(fā) 前端
離線存儲應(yīng)用程序數(shù)據(jù)已成為現(xiàn)代 Web 開發(fā)中的必要條件。內(nèi)置的瀏覽器 localStorage 可以用作簡單輕量數(shù)據(jù)的數(shù)據(jù)存儲,但是在結(jié)構(gòu)化數(shù)據(jù)或存儲大量數(shù)據(jù)方面卻不足。

[[388114]]

原文:https://blog.logrocket.com/dexie-js-indexeddb-react-apps-offline-data-storage/

作者:Ebenezer Don

離線存儲應(yīng)用程序數(shù)據(jù)已成為現(xiàn)代 Web 開發(fā)中的必要條件。內(nèi)置的瀏覽器 localStorage 可以用作簡單輕量數(shù)據(jù)的數(shù)據(jù)存儲,但是在結(jié)構(gòu)化數(shù)據(jù)或存儲大量數(shù)據(jù)方面卻不足。

最重要的是,我們只能將字符串?dāng)?shù)據(jù)存儲在受 XSS 攻擊的 localStorage 中,并且它沒有提供很多查詢數(shù)據(jù)的功能。

這就是 IndexedDB 的亮點(diǎn)。使用 IndexedDB,我們可以在瀏覽器中創(chuàng)建結(jié)構(gòu)化的數(shù)據(jù)庫,將幾乎所有內(nèi)容存儲在這些數(shù)據(jù)庫中,并對數(shù)據(jù)執(zhí)行各種類型的查詢。

在本文中,我們將了解 IndexedDB 的全部含義,以及如何使用 Dexie.js(用于 IndexedDB 的簡約包裝)處理 Web 應(yīng)用程序中的離線數(shù)據(jù)存儲。

IndexedDB 如何工作

IndexedDB 是用于瀏覽器的內(nèi)置非關(guān)系數(shù)據(jù)庫。它使開發(fā)人員能夠?qū)?shù)據(jù)持久存儲在瀏覽器中,即使在脫機(jī)時也可以無縫使用 Web 應(yīng)用程序。使用 IndexedDB 時,您會經(jīng)??吹絻蓚€術(shù)語:數(shù)據(jù)庫存儲和對象存儲。讓我們在下面進(jìn)行探討。

使用 IndexedDB 創(chuàng)建數(shù)據(jù)庫

IndexedDB 數(shù)據(jù)庫對每個 Web 應(yīng)用程序來說都是唯一的。這意味著一個應(yīng)用程序只能從與自己運(yùn)行在同一域或子域的 IndexedDB 數(shù)據(jù)庫中訪問數(shù)據(jù)。數(shù)據(jù)庫是容納對象存儲的地方,而對象存儲又包含存儲的數(shù)據(jù)。要使用 IndexedDB 數(shù)據(jù)庫,我們需要打開(或連接到)它們:

  1. const initializeDb = indexedDB.open
  2.   "name_of_database"
  3.   version 
  4. ); 

indexedDb.open() 方法中的 name_of_database 參數(shù)將用作正在創(chuàng)建的數(shù)據(jù)庫的名稱,而 version 參數(shù)是一個代表數(shù)據(jù)庫版本的數(shù)字。

在 IndexedDB 中,我們使用對象存儲來構(gòu)建數(shù)據(jù)庫的結(jié)構(gòu),并且每當(dāng)要更新數(shù)據(jù)庫結(jié)構(gòu)時,都需要將版本升級到更高的值。這意味著,如果我們從版本 1 開始,則下次要更新數(shù)據(jù)庫的結(jié)構(gòu)時,我們需要將 indexedDb.open() 方法中的版本更改為 2 或更高版本。

使用 IndexedDB 創(chuàng)建對象存儲

對象存儲類似于關(guān)系數(shù)據(jù)庫(如 PostgreSQL)中的表和文檔數(shù)據(jù)庫(如 MongoDB)中的集合。要在 IndexedDB 中創(chuàng)建對象存儲,我們需要從之前聲明的 initializeDb 變量中調(diào)用 onupgradeneeded() 方法:

  1. initializeDb.onupgradeneeded = () => { 
  2.   const database = initializeDb.result; 
  3.   database.createObjectStore("name_of_object_store", { 
  4.     autoIncrement: true
  5.   }); 
  6. }; 

在上面的代碼塊中,我們從 initializeDb.result 屬性獲取數(shù)據(jù)庫,然后使用其 createObjectStore() 方法創(chuàng)建對象存儲。第二個參數(shù) {autoIncrement:true} 告訴 IndexedDB 自動提供/增加對象存儲中項(xiàng)目的 ID。

我省略了諸如事務(wù)和游標(biāo)之類的其他術(shù)語,因?yàn)槭褂玫图?IndexedDB API 需要進(jìn)行大量工作。這就是為什么我們需要 Dexie.js,它是 IndexedDB 的簡約包裝。讓我們看看 Dexie 如何簡化創(chuàng)建數(shù)據(jù)庫,對象存儲,存儲數(shù)據(jù)以及從數(shù)據(jù)庫查詢數(shù)據(jù)的整個過程。

使用 Dexie 離線存儲數(shù)據(jù)

使用 Dexie,創(chuàng)建 IndexedDB 數(shù)據(jù)庫和對象存儲非常容易:

  1. const db = new Dexie("exampleDatabase"); 
  2. db.version(1).stores({ 
  3.   name_of_object_store: "++id, name, price"
  4.   name_of_another_object_store: "++id, title"
  5. }); 

在上面的代碼塊中,我們創(chuàng)建了一個名為 exampleDatabase 的新數(shù)據(jù)庫,并將其作為值分配給 db 變量。我們使用 db.version(version_number).stores() 方法為數(shù)據(jù)庫創(chuàng)建對象存儲。每個對象存儲的值代表了它的結(jié)構(gòu)。例如,當(dāng)在第一個對象存儲中存儲數(shù)據(jù)時,我們需要提供一個具有屬性 name 和 price 的對象。++id 選項(xiàng)的作用就像我們在創(chuàng)建對象存儲區(qū)時使用的 {autoIncrement:true} 參數(shù)一樣。

請注意,在我們的應(yīng)用程序中使用 dexie 包之前,我們需要安裝并導(dǎo)入它。當(dāng)我們開始構(gòu)建我們的演示項(xiàng)目時,我們將看到如何做到這一點(diǎn)。

我們將要建立的

對于我們的演示項(xiàng)目,我們將使用 Dexie.js 和 React 構(gòu)建一個市場列表應(yīng)用程序。我們的用戶將能夠在市場列表中添加他們打算購買的商品,刪除這些商品或?qū)⑵錁?biāo)記為已購買。

我們將看到如何使用 Dexie useLiveQuery hook 來監(jiān)視 IndexedDB 數(shù)據(jù)庫中的更改以及在數(shù)據(jù)庫更新時重新呈現(xiàn) React 組件。這是我們的應(yīng)用程序的外觀:

設(shè)置我們的應(yīng)用

首先,我們將使用為應(yīng)用程序的結(jié)構(gòu)和設(shè)計創(chuàng)建的 GitHub 模板。這里有一個模板的鏈接。點(diǎn)擊**Use this template(使用此模板)**按鈕,就會用現(xiàn)有的模板為你創(chuàng)建一個新的資源庫,然后你就可以克隆和使用這個模板。

或者,在計算機(jī)上安裝了GitHub CLI的情況下,您可以運(yùn)行以下命令從市場列表 GitHub 模板創(chuàng)建名為 market-list-app 的存儲庫:

  1. gh repo create market-list-app --template ebenezerdon/market-list-template 

完成此操作后,您可以繼續(xù)在代碼編輯器中克隆并打開您的新應(yīng)用程序。使用終端在應(yīng)用程序目錄中運(yùn)行以下命令應(yīng)安裝 npm 依賴項(xiàng)并啟動新應(yīng)用程序:

  1. npm install && npm start 

導(dǎo)航到成功消息中的本地 URL(通常為http://localhost:3000)時,您應(yīng)該能夠看到新的React應(yīng)用程序。您的新應(yīng)用應(yīng)如下所示:

當(dāng)您打開 ./src/App.js 文件時,您會注意到我們的應(yīng)用程序組件僅包含市場列表應(yīng)用程序的 JSX 代碼。我們正在使用Materialize 框架中的類進(jìn)行樣式設(shè)置,并將其 CDN 鏈接包含在 ./public/index.html 文件中。接下來,我們將看到如何使用 Dexie 創(chuàng)建和管理數(shù)據(jù)。

用 Dexie 創(chuàng)建我們的數(shù)據(jù)庫

要在我們的 React 應(yīng)用程序中使用 Dexie.js 進(jìn)行離線存儲,我們將從在終端中運(yùn)行以下命令開始,以安裝 dexie 和 dexie-react-hooks 軟件包:

  1. npm i -s dexie dexie-react-hooks 

我們將使用 dexie-react-hooks 包中的 useLiveQuery hook 來監(jiān)視更改,并在對 IndexedDB 數(shù)據(jù)庫進(jìn)行更新時重新渲染我們的 React 組件。

讓我們將以下導(dǎo)入語句添加到我們的 ./src/App.js 文件中。這將導(dǎo)入 Dexie 和 useLiveQuery hook:

  1. import Dexie from "dexie"
  2. import { useLiveQuery } from "dexie-react-hooks"

接下來,我們將創(chuàng)建一個名為 MarketList 的新數(shù)據(jù)庫,然后聲明我們的對象存儲 items:

  1. const db = new Dexie("MarketList"); 
  2. db.version(1).stores({ 
  3.   items: "++id,name,price,itemHasBeenPurchased"
  4. }); 

我們的 items 對象存儲將期待一個具有屬性name、price和 itemHasBeenPurchased 的對象,而 id 將由 Dexie 提供。在將新數(shù)據(jù)添加到對象存儲中時,我們將為 itemHasBeenPurchased 屬性使用默認(rèn)布爾值 false,然后在我們從市場清單中購買商品時將其更新為 true。

Dexie React hook

讓我們創(chuàng)建一個變量來存儲我們所有的項(xiàng)目。我們將使用 useLiveQuery 鉤子從 items 對象存儲中獲取數(shù)據(jù),并觀察其中的變化,這樣當(dāng) items 對象存儲有更新時,我們的 allItems 變量將被更新,我們的組件將用新的數(shù)據(jù)重新渲染。我們將在 App 組件內(nèi)部進(jìn)行:

  1. const App = () => { 
  2.   const allItems = useLiveQuery(() => db.items.toArray(), []); 
  3.   if (!allItems) return null 
  4.   ... 

在上面的代碼塊中,我們創(chuàng)建了一個名為 allItems 的變量,并將 useLiveQuery 鉤子作為其值。useLiveQuery 鉤子的語法類似于 React 的 useEffect 鉤子,它期望一個函數(shù)及其依賴項(xiàng)數(shù)組作為參數(shù)。我們的函數(shù)參數(shù)返回數(shù)據(jù)庫查詢。

在這里,我們以數(shù)組格式獲取 items 對象存儲中的所有數(shù)據(jù)。在下一行中,我們使用一個條件來告訴我們的組件,如果 allItems 變量是 undefined,則意味著查詢?nèi)栽诩虞d中。

將 items 添加到我們的數(shù)據(jù)庫

仍在 App 組件中,讓我們創(chuàng)建一個名為 addItemToDb 的函數(shù),我們將使用該函數(shù)向數(shù)據(jù)庫中添加項(xiàng)目。每當(dāng)我們點(diǎn)擊“ADD ITEM(添加項(xiàng)目)”按鈕時,我們都會調(diào)用此函數(shù)。請記住,每次更新數(shù)據(jù)庫時,我們的組件都會重新渲染。

  1. ... 
  2. const addItemToDb = async event => { 
  3.     event.preventDefault() 
  4.     const name = document.querySelector('.item-name').value 
  5.     const price = document.querySelector('.item-price').value 
  6.     await db.items.add({ 
  7.       name
  8.       price: Number(price), 
  9.       itemHasBeenPurchased: false 
  10.     }) 
  11.   } 
  12. ... 

在 addItemToDb 函數(shù)中,我們從表單輸入字段中獲取商品名稱和價格值,然后使用 db.[name_of_object_store].add 方法將新商品數(shù)據(jù)添加到商品對象存儲中。我們還將 itemHasBeenPurchased 屬性的默認(rèn)值設(shè)置為 false。

從我們的數(shù)據(jù)庫中刪除 items

現(xiàn)在我們有了 addItemToDb 函數(shù),讓我們創(chuàng)建一個名為 removeItemFromDb 的函數(shù)以從我們的商品對象存儲中刪除數(shù)據(jù):

  1. ... 
  2. const removeItemFromDb = async id => { 
  3.   await db.items.delete(id) 
  4. ... 

更新我們數(shù)據(jù)庫中的項(xiàng)目

接下來,我們將創(chuàng)建一個名為 markAsPurchased 的函數(shù),用于將商品標(biāo)記為已購買。我們的函數(shù)在調(diào)用時,會將物品的主鍵作為第一個參數(shù)——在本例中是 id,它將使用這個主鍵來查詢我們想要標(biāo)記為購買的物品的數(shù)據(jù)庫。取得商品后,它將其 markAsPurchased 屬性更新為 true:

  1. ... 
  2. const markAsPurchased = async (id, event) => { 
  3.   if (event.target.checked) { 
  4.     await db.items.update(id, {itemHasBeenPurchased: true}) 
  5.   } 
  6.   else { 
  7.     await db.items.update(id, {itemHasBeenPurchased: false}) 
  8.   } 
  9. ... 

在 markAsPurchased 函數(shù)中,我們使用 event 參數(shù)來獲取用戶單擊的特定輸入元素。如果選中其值,我們將itemHasBeenPurchased 屬性更新為 true,否則更新為 false。db.[name_of_object_store] .update() 方法期望該項(xiàng)目的主鍵作為其第一個參數(shù),而新對象數(shù)據(jù)作為其第二個參數(shù)。

下面是我們的 App 組件在這個階段應(yīng)該是什么樣子。

  1. ... 
  2. const App = () => { 
  3.   const allItems = useLiveQuery(() => db.items.toArray(), []); 
  4.   if (!allItems) return null 
  5.  
  6.   const addItemToDb = async event => { 
  7.     event.preventDefault() 
  8.     const name = document.querySelector('.item-name').value 
  9.     const price = document.querySelector('.item-price').value 
  10.     await db.items.add({ name, price, itemHasBeenPurchased: false }) 
  11.   } 
  12.  
  13.   const removeItemFromDb = async id => { 
  14.     await db.items.delete(id) 
  15.   } 
  16.  
  17.   const markAsPurchased = async (id, event) => { 
  18.     if (event.target.checked) { 
  19.       await db.items.update(id, {itemHasBeenPurchased: true}) 
  20.     } 
  21.     else { 
  22.       await db.items.update(id, {itemHasBeenPurchased: false}) 
  23.     } 
  24.   } 
  25.   ... 

現(xiàn)在,我們創(chuàng)建一個名為 itemData 的變量,以容納我們所有商品數(shù)據(jù)的 JSX 代碼:

  1. ... 
  2. const itemData = allItems.map(({ id, name, price, itemHasBeenPurchased }) => ( 
  3.   <div className="row" key={id}> 
  4.     <p className="col s5"
  5.       <label> 
  6.         <input 
  7.           type="checkbox" 
  8.           checked={itemHasBeenPurchased} 
  9.           onChange={event => markAsPurchased(id, event)} 
  10.         /> 
  11.         <span className="black-text">{name}</span> 
  12.       </label> 
  13.     </p> 
  14.     <p className="col s5">${price}</p> 
  15.     <i onClick={() => removeItemFromDb(id)} className="col s2 material-icons delete-button"
  16.       delete 
  17.     </i> 
  18.   </div> 
  19. )) 
  20. ... 

在 itemData 變量中,我們映射了 allItems 數(shù)據(jù)數(shù)組中的所有項(xiàng)目,然后從每個 item 對象獲取屬性 id、name、price 和 itemHasBeenPurchased。然后,我們繼續(xù)進(jìn)行操作,并用數(shù)據(jù)庫中的新動態(tài)值替換了以前的靜態(tài)數(shù)據(jù)。

注意,我們還使用了 markAsPurchased 和 removeItemFromDb 方法作為相應(yīng)按鈕的單擊事件偵聽器。我們將在下一個代碼塊中將 addItemToDb 方法添加到表單的 onSubmit 事件中。

準(zhǔn)備好 itemData 后,讓我們將 App 組件的 return 語句更新為以下 JSX 代碼:

  1. ... 
  2. return ( 
  3.   <div className="container"
  4.     <h3 className="green-text center-align">Market List App</h3> 
  5.     <form className="add-item-form" onSubmit={event => addItemToDb(event)} > 
  6.       <input type="text" className="item-name" placeholder="Name of item" required/> 
  7.       <input type="number" step=".01" className="item-price" placeholder="Price in USD" required/> 
  8.       <button type="submit" className="waves-effect waves-light btn right">Add item</button> 
  9.     </form> 
  10.     {allItems.length > 0 && 
  11.       <div className="card white darken-1"
  12.         <div className="card-content"
  13.           <form action="#"
  14.             { itemData } 
  15.           </form> 
  16.         </div> 
  17.       </div> 
  18.     } 
  19.   </div> 
  20. ... 

在 return 語句中,我們已將 itemData 變量添加到我們的項(xiàng)目列表中(items list)。我們還使用 addItemToDb 方法作為 add-item-form 的 onsubmit 值。

為了測試我們的應(yīng)用程序,我們可以返回到我們先前打開的 React 網(wǎng)頁。請記住,您的 React 應(yīng)用必須正在運(yùn)行,如果不是,請在終端上運(yùn)行命令 npm start。您的應(yīng)用應(yīng)該能夠像下面的演示一樣運(yùn)行:

我們還可以使用條件用 Dexie 查詢我們的 IndexedDB 數(shù)據(jù)庫。例如,如果我們要獲取價格高于 10 美元的所有商品,則可以執(zhí)行以下操作:

  1. const items = await db.friends 
  2.   .where("price"
  3.   .above(10) 
  4.   .toArray(); 

您可以在Dexie 文檔中查看其他查詢方法。

結(jié)束語和源碼

在本文中,我們學(xué)習(xí)了如何使用 IndexedDB 進(jìn)行離線存儲以及 Dexie.js 如何簡化該過程。我們還了解了如何使用 Dexie useLiveQuery 鉤子來監(jiān)視更改并在每次更新數(shù)據(jù)庫時重新渲染 React 組件。

由于 IndexedDB 是瀏覽器原生的,從數(shù)據(jù)庫中查詢和檢索數(shù)據(jù)比每次需要在應(yīng)用中處理數(shù)據(jù)時都要發(fā)送服務(wù)器端 API 請求要快得多,而且我們幾乎可以在 IndexedDB 數(shù)據(jù)庫中存儲任何東西。

過去使用 IndexedDB 可能對瀏覽器的支持是一個大問題,但是現(xiàn)在所有主流瀏覽器都支持它。在 Web 應(yīng)用中使用 IndexedDB 進(jìn)行離線存儲的諸多優(yōu)勢大于劣勢,將 Dexie.js 與 IndexedDB 一起使用,使得 Web 開發(fā)變得前所未有的有趣。

這是我們的演示應(yīng)用程序的GitHub庫的鏈接。

本文轉(zhuǎn)載自微信公眾號「前端全棧開發(fā)者」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系前端全棧開發(fā)者公眾號。

 

責(zé)任編輯:武曉燕 來源: 前端全棧開發(fā)者
相關(guān)推薦

2023-05-24 16:41:41

React前端

2024-12-11 08:41:18

2024-11-26 08:30:33

2024-10-24 19:25:48

2011-05-27 08:48:13

Android HTML

2017-07-14 10:10:08

Vue.jsMixin

2021-11-29 22:59:34

Go Dockertest集成

2023-10-28 16:22:21

Go接口

2024-02-07 11:44:20

NestJSRxJS異步編程

2011-12-08 10:24:53

JavaNIO

2021-02-25 11:19:37

谷歌Android開發(fā)者

2018-06-11 12:53:53

LinuxStratis本地存儲

2022-11-30 15:01:11

React技巧代碼

2022-06-10 08:01:17

ReduxReact

2024-11-25 07:00:00

箭頭函數(shù)JavaScriptReact

2023-07-28 13:55:40

便捷選項(xiàng)組件

2019-12-12 13:50:27

strace追蹤系統(tǒng)調(diào)用Linux

2021-07-26 05:24:59

Node.js SO_RESUEPORLibuv

2021-04-17 18:24:04

Vue.js嵌套路由前端

2021-05-06 08:04:37

存儲StratisCentos 8
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號