리덕스 훅

Kyoungmoon Kim·2022년 7월 26일
0

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

1) 리덕스 훅
상태, 즉, 데이터를 가져오는 것 하나, 상태를 업데이트할 수 있는 것 하나
이렇게 두 가지를 정말 많이 쓴답니다!

    // useDispatch는 데이터를 업데이트할 때,
    // useSelector는 데이터를 가져올 때 씁니다.
    import {useDispatch, useSelector} from "react-redux";

2) BucketList.js에서 redux 데이터 가져오기
useSelector((**state**) ⇒ state.bucket)
configStore.js에서 루트 리듀서를 만들었었다.
여기에서 state는 리덕스 스토어가 가진 전체 데이터예요.

    ...
    // redux 훅 중, useSelector를 가져옵니다.
    import { useSelector } from "react-redux";
   
    const BucketList = (props) => {
      let history = useHistory();
      //   이 부분은 주석처리!
      //   console.log(props);
      //   const my_lists = props.list;
      // 여기에서 state는 리덕스 스토어가 가진 전체 데이터예요.
      // 우리는 그 중, bucket 안에 들어있는 list를 가져옵니다.
      const my_lists = useSelector((state) => state.bucket.list);
      return (
        <ListStyle>
          {my_lists.map((list, index) => {
            return (
              <ItemStyle
                className="list_item"
                key={index}
                onClick={() => {
                  history.push("/detail");
                }}

                {list}
              </ItemStyle>
            );
          })}
        </ListStyle>
      );
    };
    ...
    ```

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

  • import 부터!

    // useDispatch를 가져와요!
    import {useDispatch} from "react-redux";
    // 액션생성함수도 가져오고요!
    import { createBucket } from "./redux/modules/bucket";
  • useDispatch 훅 쓰기

    const dispatch = useDispatch();
    
    const addBucketList = () => {
    
        dispatch(createBucket(text.current.value));
      };

상세페이지에서 버킷리스트 내용을 띄워보기

  1. 몇 번째 상세에 와있는 지 알기 위해, URL 파라미터를 적용하자
    // App.js
    <Route exact path="/detail/:index" component={Detail} />
//BucketList.js
   ...
         {my_lists.map((list, index) => {
           return (
             <ItemStyle
               className="list_item"
               key={index}
               onClick={() => {
 					//url 파라미터 적용
                 history.push("/detail/"+index);
               }}

               {list}
             </ItemStyle>
           );
         })}
   ...
   ```

2.상세페이지에서 버킷리스트 내용을 띄워보자

//Detail.js
// 리액트 패키지를 불러옵니다.
import React from "react";
// 라우터 훅을 불러옵니다.
import {useParams} from "react-router-dom";
// redux hook을 불러옵니다.
import { useSelector } from "react-redux";

const Detail = (props) => {
  // 스토어에서 상태값 가져오기
  const bucket_list = useSelector((state) => state.bucket.list);
  // url 파라미터에서 인덱스 가져오기
  const params = useParams();
  const bucket_index = params.index;

  return <h1>{bucket_list[bucket_index]}</h1>;
};

export default Detail;
profile
프론트 개발 공부를 정리한 블로그입니다.

0개의 댓글