TIL 210924

HYOJIN·2021년 9월 24일
0

TIL

목록 보기
11/53
post-thumbnail

오늘 한 일

리덕스 복습

  • 리덕스 모듈 생성
 // Actions

const CREATE = "bucket/CREATE";
const DELETE = 'bucket/DELETE';


// 초기값 지정

const initialState = {
  list: ["영화관 가기", "매일 책읽기", "수영 배우기", '코딩하기'],
};


// Action Creators(액션을 dispatch 하기 위해 만드는 함수)

// create에 대한 액션 생성함수
export function createBucket(bucket) {
  return { type: CREATE, bucket: bucket }; // 액션 객체 리턴, bucket - 추가할 값
}
// delete에 대한 액션 생성함수
export function deleteBucket(bucket_index){
    console.log('지울 버킷 인덱스', bucket_index)
    return {type:DELETE, bucket_index};
}


// Reducer (수정 사항을 바꿔주는 곳)

export default function reducer(state = initialState, action = {}) {
// 기본값 설정(action에 값이 안들어 온다면 빈 딕셔너리)

  switch (action.type) {
  
    case 'bucket/CREATE': {  // 액션타입이 무엇이 될것인지 
        // state.list(원래 리스트)에 action.bucket(새로운 값 -action creators) 추가
        const new_bucket_list = [...state.list, action.bucket];
        // case 문에서 리턴해주는 어떤 값이 새로운 상태값(state)이 될것임
        return { list : new_bucket_list};
    }

    case 'bucket/DELETE' : {
        console.log(state, action);
        // 삭제할 요소를 뺀 나머지를 묶은 배열 만들기
        const new_bucket_list = state.list.filter((l, idx) => { // 요소, 인덱스
            // 리턴은 true 아니면 false
            // true 일 경우 - 새로운 배열에 현재 요소가 그대로 들어감
            // false일 경우 - 새 배열에 요소가 들어가지 않음
            console.log(parseInt(action.bucket_index) !== idx, parseInt(action.bucket_index), idx);
            return  parseInt(action.bucket_index) !== idx;  
        })

        console.log(new_bucket_list);
        return  {list: new_bucket_list}; // initialState와 형식 맞추기
        // return new_bucket_list;  //bucket 안에 list라는 키값이 없어서 undefined
    }
    default:
      return state;
  }
}
  • Store 생성
// Store = 리듀서들 묶음(root reducer) + 그외 옵션들

import {createStore, combineReducers} from 'redux';
import bucket from './modules/bucket';

// 리듀서들 묶기
const rootReducer = combineReducers({bucket});

// 스토어 만들기
const store = createStore(rootReducer);

export default store;
  • 리액트 훅
// 페이지 이동 
import { useHistory } from "react-router-dom";

// 파라미터 인덱스 가져오기
import { useParams } from "react-router-dom";
  • 리덕스 훅
// 리덕스에서 데이터 가져오기
import {useSelector} from 'react-redux';

// 리덕스 수정요청
import { useDispatch } from "react-redux";
  • Action Creators(액션 생성함수) 불러오기
// create
import {createBucket} from './redux/modules/bucket'

// delete 
import { deleteBucket } from "./redux/modules/bucket";

느낀 점

모르는 것도 여러번 반복하니까 조금씩 쌓이고 있는 것 같다. 이해가 조금씩 되다 보니까 그냥 갑자기 잘할 수 있다는 자신감이 생겨버림.(내일의 나야 잘 부탁해) 포기하지말고 끝까지 물고 늘어져보자.


내일 할 일

  • 프로젝트 작업
  • 리액트 학습
profile
https://github.com/hyojin-k

0개의 댓글