TIL_59_230119

young0_0·2023년 1월 19일
0

TIL

목록 보기
58/91

59일 차 회고

  • TS

react component

모든 컴포넌트에 children을 받아 오지 않을 테니 화살표함수 에 React.FC를 쓰기보다는 function 으로 컴포넌트로 만드는 경우가 많다. 개발자바다 성향이 다르다.

1. Function

장점

  • defaultProps 가 작동하여 undefined가 뜨지 않는다.

단점

  • props type 에 children: React.ReactNode 를 선언 해줘야 한다.
type GreetingProps = {
  name: string;
  children: React.ReactNode;
  mark: string;
  onClick: (name: string) => void;
};

function Greeting = ({ name, mark, onClick }:GreetingProps) => {
  const handleClick = () => onClick(name);
  return (
    <div>
      Hello,{name}
      {mark}
      <button onClick={handleClick}>클릭~</button>
    </div>
  );

   Greeting.defaultProps={
    mark:'!'
  }
};

2. Arrow Function

장점

  • Children 이라는 props가 기본으로 탑재 되어있다. 따로 children: React.ReactNode; 를 해주지 않아도 된다.
  • 함수명 뒤에 .작성하면 자동완성이 된다.

단점

  • defaultprops 가 제대로 작동하지 않는다. undefined가 나옴 - 그래서 타입앞에 ? (mark?: string)를 붙혀주고, props에 비구조화 할당을 해줘야 한다.( mark = '!')

type GreetingProps = {
  name: string;
  //   children: React.ReactNode;
  mark?: string;
  onClick: (name: string) => void;
};

const Greeting: React.FC<GreetingProps> = ({ name, mark = '!', onClick }) => {
  const handleClick = () => onClick(name);
  return (
    <div>
      Hello,{name}
      {mark}
      <button onClick={handleClick}>클릭~</button>
    </div>
  );
};

useState

  • useState 에 제너릭을 넣어줘도 되고 안넣어줘도 된다. hook에서 알아서 파악한다.(넣어주면 타입변환을 빨리 알수 있다.)
import React, { useState } from 'react';

function Counter() {
  //const [count, setCount] = useState<number>(0);
  const [count, setCount] = useState(0);
  // 제너릭을 넣어줘도 되고 안넣어줘도 된다. hook에서 알아서 파악한다.
  // 넣어준다면 타입이 바뀌는것을 빨리 알아 챌수 있다.
  const onIncrease = () => setCount(count + 1);
  const onDecrease = () => setCount(count - 1);

  return (
    <div>
      <h1>{count}</h1>
      <div>
        <button onClick={onIncrease}>+1</button>
        <button onClick={onDecrease}>-1</button>
      </div>
    </div>
  );
}

export default Counter;

redux 설치

  1. 리덕스 설치
yarn add redux  react-redux
  1. node-module에 타입스크립를 지원하는지 확인한다.
    • redux 는 지원

  • react-redux 는 지원하지 않는다.

  1. 타입스크립트 설치
yarn add @types/react-redux
  1. 리듀서를 만들때 type 이 이렇게뜨는데 이것을 as const 로 써줘야 한다.

profile
열심히 즐기자ㅏㅏㅏㅏㅏㅏㅏ😎

0개의 댓글