useReducer

React useReducer Hook

React useReducer Hook

useReducer Hook

useReducer Hook useState Hook-ga o'xshashdir.

U maxsus holat mantiqini boshqarishga imkon beradi.

Agar siz murakkab mantiqqa ega bo'lgan bir nechta holatlarni kuzatishda o'zingizni topsangiz, useReducer foydali bo'lishi mumkin.

Sintaksis

useReducer Hook ikkita argumentni qabul qiladi.

useReducer(<reducer>, <initialState>)

reducer funksiyasi sizning maxsus holat mantiqini o'z ichiga oladi, va initialState oddiy qiymat bo'lishi mumkin, lekin odatda obyektni o'z ichiga oladi.

useReducer Hook joriy holatni va dispatch metodini qaytaradi.

Mana bir misol, useReducer ni hisoblagich ilovasida ishlatish:

Misol

import { useReducer } from 'react';
import ReactDOM from 'react-dom/client';
 
const initialTodos = [
  {
    id: 1,
    title: 'Todo 1',
    complete: false,
  },
  {
    id: 2,
    title: 'Todo 2',
    complete: false,
  },
];
 
const reducer = (state, action) => {
  switch (action.type) {
    case 'COMPLETE':
      return state.map((todo) => {
        if (todo.id === action.id) {
          return { ...todo, complete: !todo.complete };
        } else {
          return todo;
        }
      });
    default:
      return state;
  }
};
 
function Todos() {
  const [todos, dispatch] = useReducer(reducer, initialTodos);
 
  const handleComplete = (todo) => {
    dispatch({ type: 'COMPLETE', id: todo.id });
  };
 
  return (
    <>
      {todos.map((todo) => (
        <div key={todo.id}>
          <label>
            <input type="checkbox" checked={todo.complete} onChange={() => handleComplete(todo)} />
            {todo.title}
          </label>
        </div>
      ))}
    </>
  );
}
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Todos />);

Bu faqat todo tugatish holatini kuzatish uchun mantiqni o'z ichiga oladi.

Todo qo'shish, o'chirish va tugatish kabi barcha mantiqni bitta useReducer Hook ichida ko'proq harakatlarni qo'shib saqlash mumkin.

Ushbu sahifada

GitHubda tahrirlash