Làm quen với Redux trong React native

d52bb1 2024

Redux là một thư viện quản lý vùng chứa trạng thái, cho phép truy cập tương tác dễ dàng trong react. Redux tạo ra một vùng store riêng để lưu trữ dữ liệu. Khi muốn đọc ghi dữ liệu từ một component bất kỳ thì dễ dàng truy cập thông qua redux. Nếu không dùng redux thì bạn phải thao tác qua việc truyền dữ liệu từ các props của component. Nếu các component ở xa nhau thì sẽ khó khăn truy cập được dữ liệu của các component.

 

https://redux.js.org/introduction/getting-started

Cài đặt thư viện: 

npm install @reduxjs/toolkit
npm install redux
npm  install react-redux

Tạo cấu trúc thư mục:
 

src/
	redux/
		reducers/
		store/
	screens/
		TodoScreen

Bước 1: Tạo reducer

Trong thư mục reducer, tạo một file là todoReducer.js

import { createSlice } from "@reduxjs/toolkit";
//1. khai báo khởi tạo state
const initialState = {
    listTodo :[] // chứa danh sách công việc
}
//2. thiết lập cho reducer và định nghĩa các action
const todoSlice = createSlice({
    name : 'todo',
    initialState,
    reducers:{
        addTodo (state, action){
            state.listTodo.push( action.payload );
        },
          // có thêm action nào khác thì viết vào đây
       
        
    }
});
// export các thành phần để bên screen có thể sử dụng
export const {addTodo} = todoSlice.actions;
export default todoSlice.reducer;

Bước 2: Tạo store

Trong thư mục store, tạo một file là index.js

 

import { configureStore } from "@reduxjs/toolkit";
import todoReducer from "../reducers/todoReducer";
export default configureStore({
    reducer: {
        listTodo: todoReducer
    }
});

Bước 3: Tạo giao diện trong thư mục screen

Tạo một file là TodoScreen.js để thiết lập về giao diện hiển thị

 

import { useDispatch, useSelector } from "react-redux";
import { addTodo, deleteTodo, updateTodo,toggleTodoStatus } from "../redux/reducers/todoReducer";
import { Button, Text, TextInput, TouchableOpacity, View } from "react-native";
import { useState } from "react";
const TodoScreen  =()=>{
    //1. Khai báo các state để thực hiện thêm
    const [title, setTitle] = useState('');
   
    //lấy  danh sách dữ liệu
    const  listTodo =  useSelector(state=>state.listTodo.listTodo);
    // lấy đối tượng để điều khiển các action
    const dispatch = useDispatch();// của redux
    // hàm xử lý việc thêm
    const handleAddTodo = ()=>{
        let duLieuThem = { id: Math.random().toString(), title: title };
        dispatch( addTodo ( duLieuThem )  );
    }
     
    return (
         // nội dung return bạn xem trong ảnh dưới
    );
}
export default TodoScreen;

 

Bước 4: Khai báo trên file App.tsx

import React from 'react'
import { Provider } from 'react-redux'
import store from './src/redux/store'
import TodoScreen from './src/screens/TodoScreen'
const App = () => {
 return (
    <Provider store={store}>
     <TodoScreen />
    </Provider>
 )
}
export default App

Chạy ứng dụng để thử nghiệm chức năng thêm và hiển thị danh sách.

 

 

 

 

Nguồn: zezo.dev