redux

    

# redux


간단한 TODO 앱을 예로 들어 Redux에서 객체 리스트를 어떻게 관리하는지 보여드리겠습니다.


### 1. 액션 정의


```jsx

// actions.js

export const ADD_TODO = 'ADD_TODO';

export const TOGGLE_TODO = 'TOGGLE_TODO';


export const addTodo = (text) => {

  return {

    type: ADD_TODO,

    payload: {

      id: Date.now(),  // 간단하게 ID 생성

      text,

      completed: false

    }

  };

};


export const toggleTodo = (id) => {

  return {

    type: TOGGLE_TODO,

    payload: id

  };

};


```


### 2. 리듀서 작성


```jsx

// reducers.js

import { ADD_TODO, TOGGLE_TODO } from './actions';


const initialState = [];


const todosReducer = (state = initialState, action) => {

  switch (action.type) {

    case ADD_TODO:

      return [...state, action.payload];


    case TOGGLE_TODO:

      return state.map(todo =>

        todo.id === action.payload ? { ...todo, completed: !todo.completed } : todo

      );


    default:

      return state;

  }

};


export default todosReducer;


```


### 3. 스토어 생성


```jsx

// store.js

import { createStore } from 'redux';

import todosReducer from './reducers';


const store = createStore(todosReducer);


export default store;


```


createStore는 deprecated. configureStore 사용함 앗 그냥 그대로함


[https://velog.io/@201_steve/redux-createStore-deprecated](https://velog.io/@201_steve/redux-createStore-deprecated)


### 4. React와 연결


```jsx

// TodoList.js

import React from 'react';

import { useSelector, useDispatch } from 'react-redux';

import { addTodo, toggleTodo } from './actions';


function TodoList() {

  const todos = useSelector(state => state);

  const dispatch = useDispatch();


  const handleAdd = (text) => {

    dispatch(addTodo(text));

  };


  const handleToggle = (id) => {

    dispatch(toggleTodo(id));

  };


  return (

    <div>

      <input type="text" placeholder="Add todo" onKeyDown={(e) => {

        if (e.key === 'Enter' && e.target.value) {

          handleAdd(e.target.value);

          e.target.value = '';

        }

      }} />

      <ul>

        {todos.map(todo => (

          <li key={todo.id} onClick={() => handleToggle(todo.id)} style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>

            {todo.text}

          </li>

        ))}

      </ul>

    </div>

  );

}


export default TodoList;


```


이 예제에서는 TODO 항목들의 목록을 배열로 관리하고 있습니다. 각 TODO 항목은 객체 형태로 `{ id, text, completed }`의 정보를 가지고 있습니다. `addTodo` 액션을 통해 새로운 항목을 추가하고, `toggleTodo` 액션을 통해 해당 항목의 완료 상태를 토글할 수 있습니다.

댓글

이 블로그의 인기 게시물

js 스트링에서 요소 갯수 세기

STUDY

javascript cheatsheet