Javascript/상태관리

[React-Redux] 리액트에 리덕스 적용하기 - 노래 리스트 만들기(1)

codnjs779 2021. 11. 18. 02:47

일주일 정도 리덕스, 리덕스 리액트 공부를 했는데 100% 이해는 하지 못했다😂 이러다간 계속 공부만 하게될 거 같아서 일단 이해한 부분, 활용해 볼 수 있는 부분까지 정리해두고 모르는 건 다시 찾아보고 배우면서 이해하려고 한다.

아래 링크로 걸어둔 두 번째 레퍼런스를 따라서 만들어 봤다. 구현하고자 하는 기능은 노래 목록을을 화면에 출력하고, 해당 항목을 클릭할 때 그 항목의 세부사항이 나오는 기능이다.

 

여기에 추가로 input 창에 입력한 userData를 버튼을 누르면 화면에 출력하는 것까지구현해 보려려 했으나, 맘처럼 잘 안돼서,,ㅠㅠ!!! 일단 오늘은 인풋창에 입력하면 바로 화면에 출력되게까지구현해 봤다.. 방법을알게 되면 다시 이 글에 추가하려고 한다.

 

 

1. 리액트 리덕스 환경셋팅

$ create-react-app songs
$ cd songs
$ npm install redux react-redux

 

2. action creator 생성

     >> creator 리턴값으로 action 타입, 인자를 리턴해준다

//user가 클릭버튼을 누를때 발동
export const selectSong = (song) => {
    return {
        type: "SONG_SELECTED",
        payload: song, //액션 작동시 필요한 데이터
    };
};

//user가 input에 입력한 데이터를 입력할 때 발동
export const inputSong = (input) => {
    return {
        type: "USER_INPUT",
        payload: input,
    };
};

 

3. reducer 생성

1) 노래 목록 리듀서(songsReducer) & 선택된 노래목록을 알 수 있는 리듀서(selectedSongReducer)

const songsReducer = () => {
    return [
        { title: "소격동", duration: "3:30" },
        { title: "zeze", duration: "3:00" },
        { title: "coin", duration: "3:22" },
        { title: "마음", duration: "3:12" },
    ];
};


const selectedSongReducer = (selectedSong = null, action) => {
 
    if (action.type === "SONG_SELECTED") {
        return action.payload;
    }
    return selectedSong;
};

2) 인풋텍스트 리듀서

const userData = (inputTxt = "", action) => {
    if (action.type === "USER_INPUT") {
        return action.payload;
    }
    return inputTxt;
};

export default userData;

 

3) 하나로 합쳐서 전역에서 사용할 수 있도록 하기

import { combineReducers } from "redux";
import inputData from "../reducers/inputData";

const songsReducer = () => {
    return [
        { title: "소격동", duration: "3:30" },
        { title: "zeze", duration: "3:00" },
        { title: "coin", duration: "3:22" },
        { title: "마음", duration: "3:12" },
    ];
};


const selectedSongReducer = (selectedSong = null, action) => {
  
    if (action.type === "SONG_SELECTED") {
        return action.payload;
    }
    return selectedSong;
};

export default combineReducers({
    songs: songsReducer,
    selectedSong: selectedSongReducer,
    inputData: inputData,
});

 

4. index.js에 store생성

import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore } from "redux";
import App from "./components/App";
import reducers from "./reducers";
import { composeWithDevTools } from "redux-devtools-extension";

const store = createStore(reducers, composeWithDevTools());


ReactDOM.render(
    <React.StrictMode>
        <Provider store={store}>
            <App />
        </Provider>
    </React.StrictMode>,
    document.getElementById("root")
);

객체를 전역에서 사용할 수 있게 store를 생성하고, 만들어둔 리듀서들을 인자로 넣어준다. 그 다음 생성한 store를 Provider에 넣어준다. 그럼 이제 전역에서 store에 담긴 내용을 맘껏 사용할 수 있게 된다. 

 

++ redux dev tools를 사용하고 싶으면 store에 composeWithDevTools()를 추가하고 아래 명령어를 입력해서 Dev tool을 설치해주면 됨 

$ yarn add redux-devtools-extension

 이렇게 해주면 이제 전역에서 값을 사용할 수 있는 준비를 다 마치게 된다. 다음 글에서는 store에 담긴 데이터를

View에서 사용할 수 있는 방법에 대해서 포스팅 하겠다. 

 

 

*참고 자료 https://www.howdy-mj.me/redux/react-redux-intro/, https://devlog-h.tistory.com/14

 

리액트 - 리덕스(Redux) 쉽게 이해하기 (with Typescript)

안녕하세요. 휴몬랩 소프트웨어 개발자 진(JIN)입니다. 리액트를 이용해 개발하다 보면 컴포넌트(조각들)를 만들어 쪼개어 만들다 보면 많은 계층구조가 생기게 되고 state(상태)를 관리하는 게 참

devlog-h.tistory.com

 

React-redux 이해하기

Redux란? React 프로젝트의 규모가 커질때마다 자식으로 넘겨주어야 하는 props의 깊이도 점점 깊어진다. 따라서, 어디에서든 내가 원하는 state를 사용할 수 있는 라이브러리 Redux가 나타났다. Redux는

www.howdy-mj.me