React의 useReducer Hook을 사용하여 상태 관리 마스터하기

Patricia Arquette
풀어 주다: 2024-10-20 13:02:02
원래의
454명이 탐색했습니다.

React 애플리케이션을 구축할 때 상태 관리가 복잡해질 수 있으며, 특히 서로 의존하는 여러 상태 변수를 처리할 때 더욱 그렇습니다. 이런 상황에 처했다면 이제 useReducer Hook의 힘을 탐색해 볼 시간입니다!

useReducer란 무엇인가요?
useReducer Hook은 예측 가능한 방식으로 상태를 관리하기 위한 강력한 도구입니다. 이를 통해 복잡한 상태 로직을 깔끔하고 체계적인 방식으로 관리할 수 있어 코드 유지 관리가 더욱 쉬워집니다.

구문
useReducer 후크는 두 가지 인수를 허용합니다:

useReducer(reducer, initialState)

로그인 후 복사

reducer: 사용자 정의 상태 로직이 포함된 함수입니다.
initialState: 구성 요소의 초기 상태(일반적으로 객체).

작동 방식

  1. 현재 상태: 최근에 전달된 작업을 기반으로 한 현재 상태 값입니다.
  2. 디스패치 방법: 상태를 업데이트하기 위해 리듀서에 작업을 보낼 수 있는 함수

1.예:
다음은 useReducer 후크를 사용하여 카운터를 관리하는 방법에 대한 간단한 예입니다.

import React, { useReducer } from "react";

// Define the initial state
const initialState = { count: 0 };

// Define the reducer function
const reducer = (state, action) => {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    default:
      return state;
  }
};

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  // Inline styles
  const containerStyle = {
    maxWidth: "400px",
    margin: "50px auto",
    padding: "20px",
    borderRadius: "10px",
    boxShadow: "0 4px 20px rgba(0, 0, 0, 0.2)",
    textAlign: "center",
    backgroundColor: "#ffffff",
    fontFamily: "'Roboto', sans-serif",
  };

  const headingStyle = {
    fontSize: "2.5rem",
    margin: "20px 0",
    color: "#333333",
  };

  const buttonStyle = {
    margin: "10px",
    padding: "12px 24px",
    fontSize: "1.1rem",
    border: "none",
    borderRadius: "5px",
    cursor: "pointer",
    transition: "background-color 0.3s, transform 0.3s",
    outline: "none",
    boxShadow: "0 2px 10px rgba(0, 0, 0, 0.1)",
  };

  const incrementButtonStyle = {
    ...buttonStyle,
    backgroundColor: "#28a745",
    color: "white",
  };

  const decrementButtonStyle = {
    ...buttonStyle,
    backgroundColor: "#dc3545",
    color: "white",
  };

  // Hover and active styles
  const buttonHoverStyle = {
    filter: "brightness(1.1)",
    transform: "scale(1.05)",
  };

  return (
    <div style={containerStyle}>
      <h1 style={headingStyle}>Count: {state.count}</h1>
      <button
        style={incrementButtonStyle}
        onMouseOver={(e) =>
          (e.currentTarget.style = {
            ...incrementButtonStyle,
            ...buttonHoverStyle,
          })
        }
        onMouseOut={(e) => (e.currentTarget.style = incrementButtonStyle)}
        onClick={() => dispatch({ type: "increment" })}
      >
        Increment
      </button>
      <button
        style={decrementButtonStyle}
        onMouseOver={(e) =>
          (e.currentTarget.style = {
            ...decrementButtonStyle,
            ...buttonHoverStyle,
          })
        }
        onMouseOut={(e) => (e.currentTarget.style = decrementButtonStyle)}
        onClick={() => dispatch({ type: "decrement" })}
      >
        Decrement
      </button>
    </div>
  );
}

export default Counter;

로그인 후 복사

출력:

Mastering State Management with the useReducer Hook in React

2.예:

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

// Define the initial state
const initialState = {
  todos: [],
};

// Define the reducer function
const reducer = (state, action) => {
  switch (action.type) {
    case "ADD_TODO":
      return { ...state, todos: [...state.todos, action.payload] };
    case "REMOVE_TODO":
      return {
        ...state,
        todos: state.todos.filter((todo) => todo.id !== action.payload),
      };
    default:
      return state;
  }
};

function TodoApp() {
  const [state, dispatch] = useReducer(reducer, initialState);
  const [inputValue, setInputValue] = useState("");

  const handleAddTodo = () => {
    if (inputValue.trim()) {
      dispatch({
        type: "ADD_TODO",
        payload: { id: Date.now(), text: inputValue },
      });
      setInputValue(""); // Clear input field
    }
  };

  // Internal CSS
  const styles = {
    container: {
      maxWidth: "600px",
      margin: "50px auto",
      padding: "20px",
      borderRadius: "10px",
      boxShadow: "0 4px 20px rgba(0, 0, 0, 0.1)",
      backgroundColor: "#f9f9f9",
      fontFamily: "'Arial', sans-serif",
    },
    heading: {
      textAlign: "center",
      fontSize: "2.5rem",
      marginBottom: "20px",
      color: "#333",
    },
    input: {
      width: "calc(100% - 50px)",
      padding: "10px",
      borderRadius: "5px",
      border: "1px solid #ccc",
      fontSize: "1rem",
      marginRight: "10px",
    },
    button: {
      padding: "10px 15px",
      fontSize: "1rem",
      border: "none",
      borderRadius: "5px",
      backgroundColor: "#28a745",
      color: "white",
      cursor: "pointer",
      transition: "background-color 0.3s",
    },
    buttonRemove: {
      padding: "5px 10px",
      marginLeft: "10px",
      fontSize: "0.9rem",
      border: "none",
      borderRadius: "5px",
      backgroundColor: "#dc3545",
      color: "white",
      cursor: "pointer",
      transition: "background-color 0.3s",
    },
    todoList: {
      listStyleType: "none",
      padding: 0,
      marginTop: "20px",
    },
    todoItem: {
      display: "flex",
      justifyContent: "space-between",
      alignItems: "center",
      padding: "10px",
      borderBottom: "1px solid #ccc",
      backgroundColor: "#fff",
      borderRadius: "5px",
      marginBottom: "10px",
    },
  };

  return (
    <div style={styles.container}>
      <h1 style={styles.heading}>Todo List</h1>
      <div style={{ display: "flex", justifyContent: "center" }}>
        <input
          style={styles.input}
          type="text"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          placeholder="Add a new todo"
        />
        <button style={styles.button} onClick={handleAddTodo}>
          Add Todo
        </button>
      </div>
      <ul style={styles.todoList}>
        {state.todos.map((todo) => (
          <li style={styles.todoItem} key={todo.id}>
            {todo.text}
            <button
              style={styles.buttonRemove}
              onClick={() =>
                dispatch({ type: "REMOVE_TODO", payload: todo.id })
              }
            >
              Remove
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default TodoApp;

로그인 후 복사

출력:

Mastering State Management with the useReducer Hook in React

useReducerHook은 React 툴킷에 탁월한 추가 기능입니다. 이를 통해 복잡한 상태 관리를 효율적으로 처리할 수 있어 애플리케이션이 더욱 강력해지고 유지 관리가 쉬워집니다. 다음 프로젝트에서 시도해 보고 상태 관리를 한 단계 더 발전시키세요!

위 내용은 React의 useReducer Hook을 사용하여 상태 관리 마스터하기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!