Khóa học react-native

Lưu Trữ Dữ Liệu trong React Native

0 phút đọc

Lưu trữ dữ liệu là một phần quan trọng trong việc phát triển ứng dụng di động, cho phép bạn lưu trữ và truy xuất dữ liệu cục bộ trên thiết bị của người dùng. Trong React Native, có nhiều phương pháp và thư viện để lưu trữ dữ liệu, bao gồm AsyncStorage, SQLite, và Realm. Mỗi phương pháp có những ưu điểm và hạn chế riêng, phù hợp với các trường hợp sử dụng khác nhau.

AsyncStorage

AsyncStorage là một API đơn giản và không đồng bộ để lưu trữ dữ liệu cục bộ dưới dạng cặp khóa-giá trị. Nó tương tự như localStorage trong trình duyệt web, nhưng hỗ trợ các thao tác không đồng bộ.

Cài Đặt AsyncStorage

npm install @react-native-async-storage/async-storage

Sử Dụng AsyncStorage

Ví dụ:

import React, { useState, useEffect } from "react";
import { View, Text, Button, TextInput, StyleSheet } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";

const AsyncStorageExample = () => {
  const [text, setText] = useState("");
  const [storedText, setStoredText] = useState("");

  useEffect(() => {
    const loadStoredText = async () => {
      try {
        const value = await AsyncStorage.getItem("storedText");
        if (value !== null) {
          setStoredText(value);
        }
      } catch (error) {
        console.error(error);
      }
    };

    loadStoredText();
  }, []);

  const saveText = async () => {
    try {
      await AsyncStorage.setItem("storedText", text);
      setStoredText(text);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="Enter some text"
        value={text}
        onChangeText={setText}
      />
      <Button title="Save Text" onPress={saveText} />
      <Text style={styles.storedText}>Stored Text: {storedText}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    padding: 20,
  },
  input: {
    height: 40,
    borderColor: "gray",
    borderWidth: 1,
    marginBottom: 10,
    paddingHorizontal: 10,
    width: "100%",
  },
  storedText: {
    marginTop: 20,
    fontSize: 18,
  },
});

export default AsyncStorageExample;

SQLite

SQLite là một cơ sở dữ liệu quan hệ nhẹ, được tích hợp sẵn trong nhiều hệ điều hành di động. Nó cung cấp khả năng lưu trữ dữ liệu có cấu trúc và hỗ trợ các truy vấn SQL.

Cài Đặt SQLite

npm install react-native-sqlite-storage

Sử Dụng SQLite

Ví dụ:

import React, { useState, useEffect } from "react";
import { View, Text, Button, TextInput, StyleSheet } from "react-native";
import SQLite from "react-native-sqlite-storage";

const db = SQLite.openDatabase(
  {
    name: "MainDB",
    location: "default",
  },
  () => {},
  (error) => {
    console.error(error);
  }
);

const SQLiteExample = () => {
  const [text, setText] = useState("");
  const [storedText, setStoredText] = useState("");

  useEffect(() => {
    db.transaction((tx) => {
      tx.executeSql(
        "CREATE TABLE IF NOT EXISTS Texts (ID INTEGER PRIMARY KEY AUTOINCREMENT, Text TEXT);"
      );
    });

    const loadStoredText = () => {
      db.transaction((tx) => {
        tx.executeSql("SELECT * FROM Texts", [], (tx, results) => {
          if (results.rows.length > 0) {
            setStoredText(results.rows.item(0).Text);
          }
        });
      });
    };

    loadStoredText();
  }, []);

  const saveText = () => {
    db.transaction((tx) => {
      tx.executeSql("INSERT INTO Texts (Text) VALUES (?)", [text], () => {
        setStoredText(text);
      });
    });
  };

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="Enter some text"
        value={text}
        onChangeText={setText}
      />
      <Button title="Save Text" onPress={saveText} />
      <Text style={styles.storedText}>Stored Text: {storedText}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    padding: 20,
  },
  input: {
    height: 40,
    borderColor: "gray",
    borderWidth: 1,
    marginBottom: 10,
    paddingHorizontal: 10,
    width: "100%",
  },
  storedText: {
    marginTop: 20,
    fontSize: 18,
  },
});

export default SQLiteExample;

Realm

Realm là một cơ sở dữ liệu đối tượng di động, cung cấp hiệu suất cao và dễ sử dụng. Nó hỗ trợ các truy vấn phức tạp và có thể đồng bộ hóa dữ liệu với đám mây.

Cài Đặt Realm

npm install realm

Sử Dụng Realm

Ví dụ:

import React, { useState, useEffect } from "react";
import { View, Text, Button, TextInput, StyleSheet } from "react-native";
import Realm from "realm";

const TextSchema = {
  name: "Text",
  properties: {
    id: "int",
    text: "string",
  },
  primaryKey: "id",
};

const realm = new Realm({ schema: [TextSchema] });

const RealmExample = () => {
  const [text, setText] = useState("");
  const [storedText, setStoredText] = useState("");

  useEffect(() => {
    const loadStoredText = () => {
      const texts = realm.objects("Text");
      if (texts.length > 0) {
        setStoredText(texts[0].text);
      }
    };

    loadStoredText();
  }, []);

  const saveText = () => {
    realm.write(() => {
      realm.create("Text", { id: 1, text: text }, "modified");
      setStoredText(text);
    });
  };

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="Enter some text"
        value={text}
        onChangeText={setText}
      />
      <Button title="Save Text" onPress={saveText} />
      <Text style={styles.storedText}>Stored Text: {storedText}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    padding: 20,
  },
  input: {
    height: 40,
    borderColor: "gray",
    borderWidth: 1,
    marginBottom: 10,
    paddingHorizontal: 10,
    width: "100%",
  },
  storedText: {
    marginTop: 20,
    fontSize: 18,
  },
});

export default RealmExample;

So Sánh Các Phương Pháp Lưu Trữ Dữ Liệu

Phương Pháp Ưu Điểm Nhược Điểm
AsyncStorage Dễ sử dụng, không đồng bộ, phù hợp cho dữ liệu nhỏ Hiệu suất kém với dữ liệu lớn, không hỗ trợ truy vấn phức tạp
SQLite Hỗ trợ truy vấn SQL, hiệu suất cao, phù hợp cho dữ liệu có cấu trúc Cần cài đặt và cấu hình, phức tạp hơn so với AsyncStorage
Realm Hiệu suất cao, dễ sử dụng, hỗ trợ đồng bộ hóa, truy vấn phức tạp Cần cài đặt và cấu hình, kích thước thư viện lớn hơn so với các phương pháp khác

Các Kỹ Thuật Tối Ưu Hóa Lưu Trữ Dữ Liệu

Sử Dụng StyleSheet để Tối Ưu Hóa Hiệu Suất

Sử dụng StyleSheet.create để định nghĩa các style giúp tối ưu hóa hiệu suất vì các style được tạo ra chỉ một lần và được tham chiếu lại nhiều lần.

Ví dụ:

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    padding: 20,
  },
  input: {
    height: 40,
    borderColor: "gray",
    borderWidth: 1,
    marginBottom: 10,
    paddingHorizontal: 10,
    width: "100%",
  },
  storedText: {
    marginTop: 20,
    fontSize: 18,
  },
});

Tránh Sử Dụng Hàm Inline

Tránh sử dụng các hàm inline cho thuộc tính onPress để tránh việc tạo lại hàm mỗi khi component được render.

Ví dụ:

const saveText = async () => {
  try {
    await AsyncStorage.setItem("storedText", text);
    setStoredText(text);
  } catch (error) {
    console.error(error);
  }
};

<Button title="Save Text" onPress={saveText} />;

Các Hạn Chế của Các Phương Pháp Lưu Trữ Dữ Liệu

Mặc dù các phương pháp lưu trữ dữ liệu trong React Native rất mạnh mẽ, nhưng chúng cũng có một số hạn chế:

  1. Hiệu Suất: Khi lưu trữ và truy xuất dữ liệu lớn, hiệu suất của ứng dụng có thể bị ảnh hưởng.
  2. Tùy Chỉnh Giao Diện: Các phương pháp lưu trữ dữ liệu không hỗ trợ nhiều tùy chỉnh giao diện như thay đổi font chữ, thêm biểu tượng, hoặc tạo nền gradient.
  3. Quản Lý Sự Kiện: Khi có nhiều sự kiện lắng nghe được đăng ký, việc quản lý và loại bỏ chúng có thể trở nên phức tạp.

Kết Luận

Lưu trữ dữ liệu là một phần quan trọng trong việc phát triển ứng dụng di động, giúp bạn tạo ra các giao diện người dùng mượt mà và hiệu quả. Bằng cách hiểu rõ các phương pháp và cách sử dụng các thư viện lưu trữ dữ liệu như AsyncStorage, SQLite, và Realm, bạn có thể tạo ra các ứng dụng mạnh mẽ và dễ bảo trì. Hy vọng qua bài viết này, bạn đã có thể nắm bắt được cách lưu trữ dữ liệu trong React Native và áp dụng vào các dự án của mình.

Avatar
Được viết bởi

TechMely Team

Gợi ý câu hỏi phỏng vấn

Gợi ý bài viết

Bình luận

Chưa có bình luận nào

Khoá học javascript từ cơ bản đến chuyên sâuYoutube Techmely