Front-end/React

[TIL] 클래스형 컴포넌트에서 Redux payload

성중 2022. 1. 13. 10:57

클래스형 컴포넌트에서 Redux payload

reducer에 데이터를 제어하는 액션을 추가해 클래스형 컴포넌트에서 호출해보고 payload도 보내보자!

 

[Footer.js]

const mapStateToProps = (state) => {
  return {
    reduxValue: { ...state.footer },
  };
};

다른 파일에서 받은 서버 데이터가 Redux를 통해 넘어와 reduxValue에 담긴다

* Footer.js는 React Howler 라이브러리 문제로 클래스형 컴포넌트를 사용하기 때문에 useSelector()와 useDispatch()를 사용하지 못한다 ㅜㅜ

 

1. Footer 리스트 전체 삭제 (payload X)

현재 Footer 리스트는 song 데이터를 map 함수로 뿌려주고 있다

 

[Footer.js]

{reduxValue.song?.map((song) => {
  return (
    <div
      class="items_bound"

reducer 파일에 DELETEALL 액션 type을 선언하고

 

[footer.js]

const DELETEALL = 'DELETEALL';
export const deleteAll = () => ({ type: DELETEALL });

데이터를 비워주는 액션을 추가

function footer(state = initialState, action) {
  switch (action.type) {
    case 'DELETEALL':
      return {
        ...state,
        song: [],
        play: false,
        title: ' - ',
        imgThumnail:
          '기본이미지',
        src: null,
        creator: ' - ',
      };
    default:
      return state;
  }
}

mapDispatchToProp 함수로 dispatch를 넘겨준다

 

[Footer.js]

const mapDispatchToProp = (dispatch) => {
  return {
    deleteAll: () => dispatch(deleteAll()),
  };
};

import 해주고

import { deleteAll } from '../../modules/footer';

deleteAll을 props로 넘겨주고

  render() {
    const { reduxValue, stop, buttonPlay, back, next, deleteAll } = this.props;

onClick 이벤트로 넣어준다

<div className="surface_all_delete" onClick={deleteAll}>

 

2. Footer 리스트 곡 실행 (payload O)

Footer 리스트에서 클릭한 곡이 Footer에서 바로 재생되도록 해줄 것이다

다만 이 경우는 위와 달리 Footer.js에서 Redux 데이터를 payload로 보내줘야 하기 때문에 mapDispatchToProp에서 매개변수를 추가해줄 것이다

 

위에서 보았듯이 Redux에서 받은 song 데이터가 map 함수로 뿌려지고 있다

{reduxValue.song?.map((song) => {
  return (
    <div
      class="items_bound"

우선 console.log를 찍어서 song 데이터 형태를 파악해준다

 

요로코롬 들어온다

데이터 형태에 맞게 보낼 payload를 매개변수로 mapDispatchToProp에서 정의해준다

 

[Footer.js]

const mapDispatchToProp = (dispatch) => {
  return {
    deleteAll: () => dispatch(deleteAll()),
    listPlay: (song) =>
      dispatch({
        type: 'LISTPLAY',
        title: song.songName,
        imgThumnail: `url(songImg/${song.imgFile})`,
        src: '/serverSong/' + song.wavFile,
        creator: song.creatorName,
      }),
  };
};

 

payload를 받아서 넣도록 reducer에 액션 타입을 추가해준다

reducer 파일에서 이것 외에 추가 작업은 필요없다 !

 

[footer.js]

    case 'LISTPLAY':
      return {
        ...state,
        play: true,
        title: action.title,
        imgThumnail: action.imgThumnail,
        src: action.src,
        creator: action.creator,
      };
    default:
      return state;
  }

props로 넘겨주고

 

[Footer.js]

  render() {
    const { reduxValue, stop, buttonPlay, back, next, deleteAll, listPlay } =
      this.props;

map 함수 내부에서 onClick 이벤트로 호출해주자

{reduxValue.song?.map((song) => {
  return (
    <div
      class="items_bound"
      onClick={() => {
        console.log(song);
        listPlay(song);
      }}>

 

3. Footer 리스트 목록에서 삭제 (payload +로직구현)

reducer에서 액션 값과 state 값을 적절히 조합하면 이런 식으로 다양한 기능을 구현할 수 있다 

(filter 함수로 Redux의 song.songId와 action.songId가 같다면 배열에서 삭제하는 로직이다)

case 'DELETEONE':
  return {
    ...state,
    song: state.song.filter((song) => song.songId !== action.songId),
  };

payload는 자유롭게 넘겨줄 수 있다!

deleteOne: (song) =>
  dispatch({
    type: 'DELETEONE',
    songId: song.songId,
  }),

'Front-end > React' 카테고리의 다른 글

[코딩애플] #9 성능잡기  (8) 2022.01.17
[코딩애플] #8 if문 작성패턴  (2) 2022.01.13
[TIL] Redux DevTools  (2) 2022.01.11
[TIL] 데이터 Redux로 관리  (2) 2022.01.10
[TIL] React Howler 재생바 넓이  (2) 2022.01.07