잼무비

Part2-3 리덕스 연결하기

잼굴 2022. 11. 23. 16:38

리덕스 파일구조

 

 

let initialState = {
    popularMovies:{},
    topRatedMovies:{},
    upcomingMovies:{},
};

function movieReducer(state=initialState,action){
let{type,payload} = action
switch(type){
    case "GET_MOVIES_SUCCESS":
        return {...state,popularMovies: payload.popularMovies, topRatedMovies: payload.topRatedMovies, upcomingMovies: payload.upcomingMovies,};
        
default: return{...state}
}
}

export default movieReducer;

리듀서를 만들어주고 payload에 있는 데이터들 받아온다

 

       dispatch({
        type: "GET_MOVIES_SUCCESS",
        payload: {popularMovies:popularMovies.data, topRatedMovies: topRatedMovies.data, upcomingMovies: upcomingMovies.data},
       })

액션에서 데이터를 보낼수있도록 해준다 데이터 필드만 보낼수있도록 뒤에 .data 해줘야함

 

 

import { combineReducers } from "redux";
import movieReducer from "./movieReducer";
export default combineReducers({
    movie: movieReducer,
});

index.js에서 movieReducer를 combineReducer에 담아줄수있도록 해준다.

 

import React, {useEffect} from 'react'
import {movieActions} from "../redux/actions/movieActions";
import { useDispatch } from 'react-redux';
const Home = () => {
    const dispatch = useDispatch()
    useEffect(()=>{
        dispatch(movieActions.getMovies());
    },[])
  return (
    <div>Home</div>
  )
}

export default Home

물론 dispatch 연결도 해준다.

리덕스 연결 성공