끄적끄적

[React+Redux]간단하게 만들어보는 Todolist(1) 본문

React

[React+Redux]간단하게 만들어보는 Todolist(1)

2020. 11. 27. 02:34

오늘은 Redux를 이용한 아주 간단한 TodoList를 만들어보려고합니다.

 

! Redux가 무엇인지 잘 모르시는 분은 pyolog.tistory.com/7 을 참고하시면 좋을 것 같습니다.


1. 우선 cra(create-react-app)로 리액트 프로젝트를 생성하겠습니다.

npx crate-react-app redux_test

 

2. 먼저 src 폴더 밑에 store를 작성하겠습니다.

import { createStore } from "redux";

// 초기 state , 배열에 저장하겠습니다.
export const INITAIL_STATE = {todos : []};



//■■■■■■■■■■■■■■■■■■■■■■■ action 정의 ■■■■■■■■■■■■■■■■■■■■■■■■■■■
export function AddTodo(content){
    return{
        type: 'ADD',
        content
    }
}
export function DeleteTodo(id){
    return{
        type : 'DELETE',
        id
    }
}
export function UpdateTodo(id, content){
    return{
        type : 'UPDATE',
        id,
        content
    }
}


//■■■■■■■■■■■■■■■■■■■■■■■ reducer 정의 ■■■■■■■■■■■■■■■■■■■■■■■■■■■
export const Reducer = (state = INITAIL_STATE, action)=> {
    switch(action.type){
        case 'ADD' :
            return {
                ...state, 
                todos : [...state.todos, action.content]
            };
        case 'DELETE' :
            return{
                ...state,
                todos : state.todos.filter((data,index) => index !== action.id)
            }
        case 'UPDATE' :
            return{
                ...state,
                todos : state.todos.map((data,index)=>{
                    if(index === action.id){
                        return action.content;
                    }else return data;
                })
            }
        default :
            return state;
    }
}

export const store = createStore(Reducer);
export default store;

저희가 투두리스트에서 사용할 기능들은 생성, 수정, 삭제 크게 3가지 입니다.

 

 

3. index.js에 store연결하기

// 연결시켜주기위해 필요한 파일들을 가져옵니다
import store from './store';
import { Provider } from 'react-redux';
ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>
, document.getElementById("root")
);

 

 

이제 어느정도 연결이 완료되었습니다.

다음 글에서 컴포넌트들의 작성을 해보도록 하겠습니다.

Comments