Persistent state

Persistent state

2020/09/01
2021/05/07 (微調內容)

簡介

狀態(state)的儲存有兩種主要的形式,第一種目前為止所介紹的方式,會因為手機app關閉或重啟而消失,第二種是是persistent,也就是不會因為手機應用程式關閉而消失。儲存persistent state有兩種方式,一種方式是利用雲端服務儲存到遠端的資料庫(如:mySQL、airtable、firestore),另一種方式是儲存在手機上,儲存的方式也有兩大種,透過資料庫或不透過資料庫。手機可以將資料儲存在本地的資料庫(如:SQLite),但是,一般而言,如果大部份的資料已經存在雲端,那就只需要儲存一些基本的設定或偏好,這時候就可以不使用資料庫。

我們可以在手機上儲存一些個人資料,例如一些基本的設定或偏好,最簡單的方式是利用Async Storage。但是,如果儲存的資料包括了機敏性資料,建議使用加密的SecureStore或SensitiveInfo。SecureStore是expo所提供的API,SensitiveInfo則無法在expo上使用。

未加密

加密

我們可以利用SecureStore來儲存密碼等機敏性資料。

首先,要先安裝SecureStore:

expo install expo-secure-store

要先引用SecureStore:

import * as SecureStore from 'expo-secure-store';

儲存

利用

SecureStore.setItemAsync(key, value, options)

因為回傳的是個promise,就必須利用async/await來處理回傳值 。

如果只是儲存字串:

const loginString="ben";

await SecureStore.setItemAsync("login", loginString);

如果是儲存一個物件,先將物件轉成JSON字串

const login = {email:"benwu@im.fju.edu.tw", password:"password"}

const loginString = JSON.stringify(login);

await SecureStore.setItemAsync("login", loginString);

儲存密碼。

取得

利用

SecureStore.getItemAsync(key, options)

取得儲存的密碼。如果是字串

let loginString = await SecureStore.getItemAsync("login")

如果內容是JSON字串物件,要利用parse轉成物件:

let loginString = await SecureStore.getItemAsync("login")

const login = JSON.parse(loginString);

刪除

利用

SecureStore.deleteItemAsync(key, options)

清除帳號、密碼。例如:

await SecureStore.deleteItemAsync("login");

資料庫