hmk run dev

리덕스 모듈 + 스토어 , 스토어 사용방법 세세하게 본문

React

리덕스 모듈 + 스토어 , 스토어 사용방법 세세하게

hmk run dev 2021. 3. 23. 20:27

일단 리덕스모듈과 그것을 담아줄 스토어를 만들어야한다

 

schedule.js

//Action 액션의 변수는 전부 대문자 약속~
//모듈명 소문자 액션명 대문자
//우리가 만든기낭 스케줄 띄워주는거 = load/ 스케줄 만드는것 create
const LOAD = "schedule/LOAD";
const CREATE = "schedule/CREATE";

const initialState = {
  list: ["영화관 가기", "매일 책읽기", "수영 배우기"], //맨처음 state 초기값
};

//Action Creator

//액션 생성 함수는 액션을 반환해줘야 하는 함수다
//액션 생성 함수는 컴포넌트들에게서 불러와야한다 export
//export는 export default와 다르게 import시 중괄호로 묶어줘야하며 ,를 통해 여러개를 써줄 수 있다
export const lodaSchedule = (schedule) => {
  //파라미터를 줄 필요는 없지만 그래도 써주자
  return { type: LOAD, schedule };
};

//데이터도 넣어 줘야한다 뭘 추가 해줘야할지의 데이터가 있어야 하니까
//여기선 파라미터로 schedule로 넘겨준다 이것은 인풋박스의 입력값을 뜻한다
export const createSchedule = (schedule) => {
  return { type: CREATE, schedule };
};

//Reducer
// reducer를 내보내 줄건데 파라미터를 두개 가져온다
// state를 안넘겨줘도 된다 하지만 기본값이 있으므로 initialState 그냥 넣어준다
export default function reducer(state =  initialState , action = {}) { //{} 실수하지말자 ㅜㅜ
  switch (action.type) {
    //LOAD할때는 기본값 initialState를 주는데 이것을 state라고 지정해뒀으니 return state
    case "schedule/LOAD": {
      return state;
    }
    // text를 받아와서 새 배열을 만들고 새 배열을 어떤 딕셔너리 안에 있는 리스트라는 키값에 새배열을 넣어줘야한다
    case "schedule/CREATE": {
      // 새배열 만들기 >>  기존배열 ...state.list + 새 텍스트 action.schedule

      const new_schedule_list = [...state.list, action.schedule];
      return { list: new_schedule_list }; //딕셔너리 리스트 안에 우리가 만든 새 리스트 넣어준다
    }
    default:
      return state;
  }
}

configStore

import { createStore, combineReducers } from "redux";
import schedule from "./modules/schedule";
import { createBrowserHistory } from "history";

export const history = createBrowserHistory(); //이건 그냥 따라 치라고 하셨다 뭘까?

//한 프로젝트에는 스토어 하나 그리고 그 스토오엔 Reducer 하나만 들어갈 수 있다
//비록 지금 리듀서가 1개지만 여러개라면 뭉쳐서 스토어에 보내줘야한다 > combineReducers
const rootReducer = combineReducers({ schedule });

const store = createStore(rootReducer); // 우리의 스토어 완성!

export default store;

 

컴포넌트와 스토어 연결하기

 

index.js

 

import { Provider } from "react-redux"

import store from "./redux/configStore"; 가져오기

아래처럼 Provider 로 감싸고 store = {store} 넣어주기

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import {BrowserRouter} from 'react-router-dom';

// 우리의 버킷리스트에 리덕스를 주입해줄 프로바이더를 불러옵니다!
import { Provider } from "react-redux";
// 연결할 스토어도 가지고 와요.
import store from "./redux/configStore";
ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>,
  document.getElementById("root")
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

 

연결해도 아직은 눈으로 보이는 차이는 없다

 

스토어에 데이터가 어떻게 들어가 있는지 어떻게 데이터를 다루는지 알아보자

 

컴포넌트에서 리덕스 데이터 사용하기

 

1. 리덕스 모듈과 connect 함수(컴포넌트 리덕스 연결)를 불러온다

 

App.js에

import { connect } from "react-redux" 

 

2. 상태값을 가져오는 함수와 액션 생성함수를 부르는 함수를 만들어준다 (dispatch)

 

커넥트를 하기위해선 두개의 함수를 준비해준다.

 

const mapStateToProps = (state) => {
  return { schedule_list: state.schedule.list }; //모듈에 schedule 참고
}; //리덕스 스토어에 있는 state상태 값을 props로 App.js에 넘겨준다

const mapDispatchToProps = (dispatch) => {
  return {
    //우리가 모듈에서 만들 액션생성 함수를 넣어주면 된다
    load: () => {
      dispatch(lodaSchedule());
    },

    create: (schedule) => {
      //크리에이트 생성 해주려면 일종의 text이 필요하다 그것을 schedule 이라고 정해준다
      dispatch(createSchedule(schedule));
    },
  };
}; // 액션이 생기는 것을 감시하는 디스패치를 넘겨주는 함수

 

3. connect로 컴포넌트와 스토어를 엮는다

 

App.js 맨밑

export default connect(mapStateToProps, mapDispatchToProps)(withRouter(App));

 

4. 콘솔에 this.props를 찍어본다 연결확인

 

create, load, schedule_list // 이 세개가 콘솔로 잘찍혀 있나 확인

 componentDidMount() {
    console.log(this.props);
  }

5. this.state 에 있는 list를 지우고 스토어에 있는 값으로교체 (이제 데이터는 리덕스에서 관리)

   <Schedule
                history={this.props.history}
                list={this.props.schedules}
              />

 

6. setState를 this.props.create로 바꾼다(리덕스 스토어에 추가한다)

이제 state가 지워졌으니 다시 스케줄 추가기능하는 방법 만들기 

  addSchdule = () => {
    const new_schedule = this.text.current.value;
    this.props.create(new_schedule);
  };

함수형 컴포넌트 훅사용해서 액션생성함수 불러보고 리스트도 가져오기

 

import { useDispatchuseSelector } from "react-redux" 일단 위에 적고

 

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

const Schedule = (props) => {
  // 소괄호 안에 props대신 list를 쓴 이유는
  // 안에 있는 밸류값만 가져오고 싶기 때문
  //   const my_schedules = props.list;
  const schedule_list = useSelector((state) => state.schedule.list);
  // store에서 값 가져온다
  //   console.log(props);
  return (
    <ListStyle>
      <div
        style={{
      		height: "100px"
        }}
      >
        스케줄 목록
      </div>
      {schedule_list.map((list, index) => { // props없이도 useSelect 이용해서 씀
        // 배열순서 정해줌
        return (
          <ItemStyle
            key={index}
            onClick={() => {
              props.history.push("/detail");
            }}
          >
            {list}
          </ItemStyle>
Comments