Today I Learned 2023.02.28. [React 프로젝트 2]

Dongchan Alex Kim·2023년 2월 28일
1

Today I Learned

목록 보기
13/31
post-thumbnail

문제상황

배경화면이 전체적으로 덮여지지 않는 현상이 있었다.
그래서 이런 저런 css명령어를 써봤는데 계속 배경이 겹치기도 하고, 반복되기도 하고 하면서 이상한 형체를 갖췄다.

시도한 것들

body{
	background-image: url("/images/attach/earth.jpg");
    background-repeat: no-repeat;
    background-size : cover;
}

해결

  • background-image -> 이미지 불러오기
  • background-repeat -> 배경화면 반복에 관한 제어문
  • background-size:cover -> 지정한 요소를 다 덮도록 배경이미지를 확대/축소
html{
	width:100%;
    height:100%;
}

body 위에 있는 html박스 안에서 100%로 정해주면, 배경 전체가 덮여진다.


리액트 아이콘

npm install react-icons --save
yarn add react-icons

import { FaPlus } from "react-icons/fa";

useReducer

const [<상태 객체>, <dispatch 함수>] = useReducer(<reducer 함수>, <초기 상태>, <초기 함수>)

reducer 함수는 현재 상태 (state) 객체와 행동(action) 객체를 인자로 받아서 새로운 상태(state) 객체를 반환하는 함수이다.

import React, { useReducer } from "react";

function reducer(state, action) {
  switch (action.type) {
    case "decrement":
      // action의 type이 "decrement"일 때, 현재 state 객체의 count에서 1을 뺀 값을 반환함
      return { count: state.count - 1 };
    case "increment":
      // action의 type이 "increment"일 때, 현재 state 객체의 count에서 1을 더한 값을 반환함
      return { count: state.count + 1 };
    default:
      // 정의되지 않은 action type이 넘어왔을 때는 에러를 발생시킴
      throw new Error("Unsupported action type:", action.type);
  }
}

function Counter() {
  const [number, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <>
      {/* 현재 카운트 값은 state인 number 객체의 count로부터 읽어옴 */}
      <h1>Count: {number.count}</h1>
      {/* 카운트 값의 변경을 위해 각 버튼이 클릭되면 dispatch 함수가 발동되면서 reducer 함수가 실행됨.
          dispatch 함수의 인자로, action 객체가 설정되었는데,
          action 객체의 type에는 어떤 버튼을 클릭하였는지에 따라
          "decrement" 또는 "increment"가 들어감
      */}
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
    </>
  );
}

export default Counter;
  1. aciton
  • action은 업데이트를 위한 정보를 가지고 있는 것이며, dispatch의 인자가 되며, reducer 함수의 두번째 인자인 action에 할당된다.
  • 아래의 코드와 같이 주로 type라는 값을 지닌 객체 형태로 사용된다.
  1. dispatch 함수
  • dispatch 함수의 인자로써 업데이트를 위한 정보를 가진 action를 이용하여, 컴포넌트 내에서 state의 업데이트를 일으키기 위해서 사용된다.
  • dispatch 함수의 인자인 action은 reducer 함수의 두번째 인자인 action에 할당된다.

useContext

App.js

import React, { createContext } from "react";
import Children from "./Children";

export const AppContext = createContext();

const App = () => {
  const user = {
    name: "김동찬",
    job: "말년병장"
  };

  return (
    <>
      <AppContext.Provider value={user}>
        <div>
          <Children />
        </div>
      </AppContext.Provider>
    </>
  );
};

export default App

Children.js

import React, { useContext } from "react";
import { AppContext } from "./App";

const Children = () => {
  // useContext를 이용해서 따로 불러온다.
  const user = useContext(AppContext);
  return (
    <>
      <h3>AppContext에 존재하는 값의 name은 {user.name}입니다.</h3>
      <h3>AppContext에 존재하는 값의 job은 {user.job}입니다.</h3>
    </>
  );
};

export default Children

useContext를 이용하면 단계마다 일일이 props를 넘겨주지 않고도 컴포넌트 트리 전체에 데이터를 제공할 수 있다.
-> 데이터가 필요할 때마다 props를 통해 전달할 필요가 없이 context 를 이용해 공유한다.

profile
Disciplined, Be systemic

1개의 댓글

comment-user-thumbnail
2023년 3월 2일

잘 봤습니당ㅎㅎㅎ useContext 공부할 때 참고할게요~!!

답글 달기