Khóa học react-native

State trong React Native

0 phút đọc

State là một khái niệm quan trọng trong React Native, giúp quản lý dữ liệu động và điều khiển giao diện người dùng. Trong bài viết này, chúng ta sẽ tìm hiểu chi tiết về state trong React Native, cách sử dụng state, các phương pháp quản lý state, và các ví dụ cụ thể để minh họa.

Giới Thiệu về State

State trong React Native là một đối tượng JavaScript lưu trữ dữ liệu có thể thay đổi theo thời gian. Nó quyết định cách một component hiển thị và hoạt động. Khi state thay đổi, component sẽ tự động re-render để phản ánh sự thay đổi đó.

Khái Niệm Cơ Bản

  • State: Là dữ liệu nội bộ của component, có thể thay đổi và được quản lý bởi chính component đó.
  • Props: Là dữ liệu được truyền từ component cha xuống component con, không thể thay đổi bởi component nhận.

Tạo và Sử Dụng State

Sử Dụng Class Component

Trong các class component, state được khởi tạo trong constructor và có thể được cập nhật bằng phương thức setState.

Ví dụ:

import React, { Component } from "react";
import { View, Text, Button, StyleSheet } from "react-native";

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.text}>Count: {this.state.count}</Text>
        <Button title="Increment" onPress={this.increment} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  text: {
    fontSize: 20,
  },
});

export default Counter;

Trong ví dụ trên, state count được khởi tạo với giá trị 0 và được cập nhật mỗi khi người dùng nhấn nút "Increment".

Sử Dụng Functional Component với Hooks

Với sự ra đời của React Hooks, chúng ta có thể sử dụng state trong các functional component bằng hook useState.

Ví dụ:

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

const Counter = () => {
  const [count, setCount] = useState(0);

  return (
    <View style={styles.container}>
      <Text style={styles.text}>Count: {count}</Text>
      <Button title="Increment" onPress={() => setCount(count + 1)} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  text: {
    fontSize: 20,
  },
});

export default Counter;

Trong ví dụ này, hook useState được sử dụng để khởi tạo state count và hàm setCount để cập nhật state.

Quản Lý State trong Ứng Dụng Phức Tạp

Khi ứng dụng trở nên phức tạp hơn, việc quản lý state giữa nhiều component trở nên khó khăn. Để giải quyết vấn đề này, chúng ta có thể sử dụng các thư viện quản lý state như Redux, MobX, hoặc Context API.

Redux

Redux là một thư viện quản lý state phổ biến, cung cấp một store toàn cục để lưu trữ toàn bộ state của ứng dụng.

Cài Đặt Redux:

npm install redux react-redux

Cấu Hình Redux:

  1. Tạo Store:
import { createStore } from "redux";

const initialState = {
  count: 0,
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case "INCREMENT":
      return { count: state.count + 1 };
    default:
      return state;
  }
};

const store = createStore(reducer);

export default store;
  1. Kết Nối Store với Ứng Dụng:
import React from "react";
import { Provider } from "react-redux";
import store from "./store";
import Counter from "./Counter";

const App = () => (
  <Provider store={store}>
    <Counter />
  </Provider>
);

export default App;
  1. Sử Dụng Redux trong Component:
import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { View, Text, Button, StyleSheet } from "react-native";

const Counter = () => {
  const count = useSelector((state) => state.count);
  const dispatch = useDispatch();

  return (
    <View style={styles.container}>
      <Text style={styles.text}>Count: {count}</Text>
      <Button
        title="Increment"
        onPress={() => dispatch({ type: "INCREMENT" })}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  text: {
    fontSize: 20,
  },
});

export default Counter;

Context API

Context API là một giải pháp tích hợp sẵn trong React để quản lý state toàn cục mà không cần phải sử dụng các thư viện bên ngoài.

Tạo Context:

import React, { createContext, useState } from "react";

export const CountContext = createContext();

export const CountProvider = ({ children }) => {
  const [count, setCount] = useState(0);

  return (
    <CountContext.Provider value={{ count, setCount }}>
      {children}
    </CountContext.Provider>
  );
};

Sử Dụng Context trong Component:

import React, { useContext } from "react";
import { View, Text, Button, StyleSheet } from "react-native";
import { CountContext } from "./CountContext";

const Counter = () => {
  const { count, setCount } = useContext(CountContext);

  return (
    <View style={styles.container}>
      <Text style={styles.text}>Count: {count}</Text>
      <Button title="Increment" onPress={() => setCount(count + 1)} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  text: {
    fontSize: 20,
  },
});

export default Counter;

Kết Nối Context với Ứng Dụng:

import React from "react";
import { CountProvider } from "./CountContext";
import Counter from "./Counter";

const App = () => (
  <CountProvider>
    <Counter />
  </CountProvider>
);

export default App;

Các Thư Viện Quản Lý State Khác

Ngoài Redux và Context API, còn nhiều thư viện khác giúp quản lý state trong React Native như MobX, Recoil, và Zustand.

MobX

MobX là một thư viện quản lý state dựa trên các khái niệm về observables, computed values, và actions.

Cài Đặt MobX:

npm install mobx mobx-react

Sử Dụng MobX:

import { observable, action } from "mobx";
import { observer } from "mobx-react";
import React from "react";
import { View, Text, Button, StyleSheet } from "react-native";

class CounterStore {
  @observable count = 0;

  @action increment = () => {
    this.count += 1;
  };
}

const store = new CounterStore();

const Counter = observer(() => (
  <View style={styles.container}>
    <Text style={styles.text}>Count: {store.count}</Text>
    <Button title="Increment" onPress={store.increment} />
  </View>
));

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  text: {
    fontSize: 20,
  },
});

export default Counter;

Kết Luận

State là một phần quan trọng trong việc phát triển ứng dụng React Native, giúp quản lý dữ liệu động và điều khiển giao diện người dùng. Bằng cách sử dụng các phương pháp và thư viện quản lý state như Redux, Context API, và MobX, bạn có thể xây dựng 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 sử dụng state 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