Ming's develop story

Chapter3 - 컴포넌트에서 리덕트 데이터 사용 및 상세페이지와 연결 본문

스파르타코딩클럽 - 항해99/항해99 Chapter3 - react 주특기 기본

Chapter3 - 컴포넌트에서 리덕트 데이터 사용 및 상세페이지와 연결

Ming 2021. 11. 23. 04:08

1. 리덕스 훅

 

리덕스도 훅이 있는데 상태, 즉, 데이터를 가져오는 것 하나, 상태를 업데이트할 수 있는 것 하나

이렇게 두 가지를 정말 많이 쓴다!  더 많은 (훅 보러가기→)

 

// useDispatch는 데이터를 업데이트할 때,

// useSelector는 데이터를 가져올 때 씁니다. 

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

2. BucketList.js에서 redux 데이터 가져오기

const data = useSelector((state) => state.bucket.list);
  //앞의 state는 스토어가 갖고있는 전체 데이터 뒤는 리턴하는 값
  console.log(data);

이런식으로 콘솔로 확인해서 내가 가져오려는 state의 값중 리스트 값을 찾아 불러와준다. 

 
console.log(props);
  const my_lists = props.list;

이는 위와 같이 버킷리스트 함수에서 프롭스를 통해 가져오는것을 대체할 수 있다.\

 
 const my_lists = useSelector((state) => state.bucket.list);

이후 원래의 값과 일치시켜주기 위해 my_lists로 변경해준다.

 

Tip. 만약 잘 작동하는지 한번 더 확인하고 싶으면 모듈의 initialState 리스트에 값을 하나 추가해보자

 

 

3. App.js에서 redux 데이터 추가하기

 

import { useDispatch } from "react-redux";

추가하기 기능을 구현했던 App.js에서 useDispatch를 import 해준다.

 

 const dispatch = useDispatch();
 
이후 dispatch = useDispatch()를 선언 하고 추가하기 버튼의 온클릭에서 불렀던 addBucketList함수를 확인해보자!
 
 
dispatch({type: "", data});

함수 안에 위와같이 dispatch를 불러오고 액션함수 객체를 불러와야 하는데 매번 저 형식으로 불러오기 귀찮기 때문에

 
import { createBucket } from "./redux/modules/bucket";

bucket.js에 만들어 두었던 액션객체를 리턴해주는 함수 createBucket을 import 해주고, 

 

const addBucketList = () => {
    // 스프레드 문법! 기억하고 계신가요? :)
    // 원본 배열 list에 새로운 요소를 추가해주었습니다.
    // setList([...list, text.current.value]); <- 이전에 추가하는 값을 불러오던 것

    dispatch(createBucket(text.current.value));
  };

위와같이 작성해주면 끝~~

 

4. 상세 페이지로 파라미터 값 넘기고 불러오기

<Route path="/detail/:index" component={Detail} />

url로 파라미터 값을 넘기려면 path 주소 뒤에  /: 를 붙여준다! (App.js)

이후 Detail 컴포넌트에서 파라미터를 가져와야한다

import React from "react";
import { useParams } from "react-router-dom";

const Detail = (props) => {
  const index = useParams();

  console.log(index);
  return <h1>상세 페이지입니다!</h1>;
};

export default Detail;

useParams를 import해주고 useParams를 지정해준다.

이후 파라미터 값이 잘 넘어오는지 console.log로 확인하는데 오류가 난다.

왜냐하면 BucketList.js에서의 온클릭 주소를 변경해주지 않았기 때문이다!

history.push("/detail/" + index);

위와 같이 BucketList.js의 온클릭 부분에 detail 뒤에 /와 "" 바깥에 + index를 추가해준다.

 

그러면 위와 같이 url에 인덱스 번호가 붙으며 상세페이지도 잘 나오는 것을 확인할 수 있다.

 

 

이젠 값을 불러올 차례!!

import { useSelector } from "react-redux";

값을 불러오는 useSelector를 Detail.js에서 import 해준다.

 

const bucket_list = useSelector((state) => state.bucket.list);
console.log(bucket_list);

아까 배웠던 방법으로 리스트를 불러오고 잘 나오는지 console.log로 확인!!

console.log(bucket_list[index.index]);
//아까{ index: 0, index: 1 }이런식으로 저장되도록 지정을 해놨기 때문에 리스트의 index번째(파라미터 값)꺼의 지정해놓은 index값을 가져와 본다. 

 

  const params = useParams();
  const bucket_index = params.index

근데 헷갈리기 쉽기 때문에 아까 지정해놓은 const index = useParams를 param으로

버킷리스트의 찐 인덱스는 const bucket_index = params.index로 지정해보자

console.log(bucket_index);

콘솔을 통해 값이 잘 나오는지 확인해보고

import React from "react";
import { useParams } from "react-router-dom";
import { useSelector } from "react-redux";

const Detail = (props) => {
  const params = useParams();
  const bucket_index = params.index;
  const bucket_list = useSelector((state) => state.bucket.list);

  return <h1>{bucket_list[bucket_index]}의 상세 페이지입니다!</h1>;
};

export default Detail;

받아서 불러온 그 값을 적용해보자!

굿~ㅋㅋ

 

Comments