State Management Framework: AppStorage and PersistentStorage
I. AppStorage: Global State Management
Function Positioning: AppStorage serves as the central storage for application-level shared states, supporting data synchronization and two-way binding across multiple components.
- @StorageLink: Implements two-way data binding between components and AppStorage. Any modification to the component data automatically updates the global state.
@Entry
@Component
struct HomePage {
@StorageLink('theme') theme: string = 'light'; // Two-way binding
build() {
Column() {
Text('Current Theme: ' + this.theme)
.onClick(() => {
this.theme = this.theme === 'light' ? 'dark' : 'light'; // Change takes effect globally
})
}
}
}
- @StorageProp: Implements one-way data binding, synchronizing data from AppStorage to the component.
II. PersistentStorage: Integration of Persistent Storage
Functional Characteristics: PersistentStorage automatically persists data from AppStorage to a local XML file, supporting state recovery after application restart.
- Initialization Rule: PersistentStorage.PersistProp only takes effect on the first initialization. Subsequent data changes are automatically synchronized.
// Initialize persistent data
PersistentStorage.PersistProp('userName', 'Guest');
PersistentStorage.PersistProp('theme', 'light');
// Bind persistent data in components
@Component
struct ProfilePage {
@StorageLink('userName') userName: string;
}
III. Data Persistence Implementation
1. User Preferences
Applicable Scenarios: Lightweight key-value storage for user settings and application configurations.
- Development Process:
import { preferences } from '@kit.ArkData';
// Write data
let pref = await preferences.getPreferences(this.context, 'user_settings');
await pref.put('fontSize', 16);
// Read data
let fontSize = await pref.get('fontSize', 14);
2. Key-Value Database (KV-Store)
Core Advantages: Supports distributed scenarios, enabling cross-device data synchronization with low conflict resolution costs.
- Typical Applications: Structured data storage for shopping cart information and user session states.
import { distributedKVStore } from '@kit.ArkData';
// Create database
const options: distributedKVStore.Options = {
schema: {
fields: { 'productId': 'string', 'count': 'integer' }
}
};
let kvManager = distributedKVStore.createKVManager(options);
// Insert data
let entry: distributedKVStore.Entry = { key: 'cart_001', value: { productId: 'P100', count: 2 } };
await kvManager.put(entry);
3. File Storage and SQLite
- File Storage: Suitable for unstructured data storage of large files, such as images and logs.
- SQLite: The preferred relational database for complex query scenarios, such as report generation and data analysis.
import fileio from '@ohos.fileio';
// Write to file
let filePath = 'data/user.txt';
let data = 'Hello, HarmonyOS!';
fileio.writeText(filePath, data);
IV. Best Practices and Performance Optimization
1. State Management Strategy
-
Layered Design:
- Use AppStorage for global states (e.g., user login status).
- Use @State or @link for local states (e.g., form inputs).
- Avoid Over-Persistence: Enable PersistentStorage only for critical data that needs recovery.
2. Persistence Performance Optimization
Solution | Read/Write Speed | Data Scale | Applicable Scenario |
---|---|---|---|
Preferences | Fast | <1MB | Configuration items, toggle states |
KV-Store | Medium | <10MB | Structured business data |
SQLite | Slow | >10MB | Complex queries and transaction operations |
3. Security and Encryption
- Sensitive Data Encryption: Use the @ohos.security module to encrypt sensitive data like passwords and tokens.
- Permission Control: Restrict database and file access permissions using ohos.permission.
Top comments (0)