새로운 프로젝트를 시작하면서 지난주 강의 때, 코드리뷰를 다시 리뷰해보는 시간을 가졌다.
return (
<>
<div
id="screen"
className={this.state.state}
onClick={this.onClickScreen}
>
{this.state.message}
</div>
{this.state.result.length === 0 ? null :
<div>평균 시간: {this.state.result.reduce((a, c)
=> a + c) / this.state.result.length}ms</div>}
</>
);
이런 코드를 작성해야 할때, return 안에서 쓰지말고
밖으로 빼버리자.
renderAverage = () => {
const { result } = this.state;
return result.length === 0? null
: <div>평균 시간: {this.state.result.reduce((a, c)
=> a + c) / this.state.result.length}ms</div>
};
return (
<>
<div
id="screen"
className={this.state.state}
onClick={this.onClickScreen}
>
{this.state.message}
</div>
{this.renderAverage()}
</>
);
또다른 예,
위와같은 경우
이렇게 변수로 꺼내서 쓰기.
list는 컴포넌트로 만들어서 분리하고
그럼 최종적으로
이렇게 깔끔하게 쓸수 있다.
const prevMovieList = React.useMemo(
(): React.ReactElement[] =>
prevMovies.map(movie:IMovie, index: number) =>
<Movie key={`${movie.imdbId}-${index}`} movie={movie}/>
), [prevMovies])
return(
...
{prevMovieList}
)
React + Typescript 조합으로 개발을 하면서 자주 사용하는 타입
리액트에서 함수형 컴포넌트의 타입을 선언할 때 사용할 수 있게 React 에서 제공중인 타입
FC 타입은 다음과 같은 형태로 사용한다.
interface AppProps {
name: string;
}
const App: React.FC<AppProps> = (props) => {
return <div>hello {props.name}</div>
}
FC 타입의 단점으로
1. 암묵적으로 children props 가 포함된다.
2. 제네릭 문법을 지원하지 않는다.
3. 불필요한 속성들을 포함한다.
이 있어서 지양하는 것이 좋다.
굳이 함수형 컴포넌트에 FC 타입을 선언하지 않고도 컴포넌트에 선언이 가능하다. props 에 직접 타입을 정의해주는 것이다. 간단하면서 props 의 구성을 가장 명확하게 선언할 수 있다.
interface AppProps {
name: string;
}
const App = (props: AppProps) => {};
react-helmet
웹 문서의 헤더 값을 변경할 때 사용하는 리액트 컴포넌트
참고 url)
https://github.com/nfl/react-helmet
$yarn add react-helmet
import React from "react";
import {Helmet} from "react-helmet";
class Application extends React.Component {
render () {
return (
<div className="application">
<Helmet>
<meta charSet="utf-8" />
<title>My Title</title>
<link rel="canonical" href="http://mysite.com/example" />
</Helmet>
...
</div>
);
}
};
<Parent>
<Helmet>
<title>My Title</title>
<meta name="description" content="Helmet application" />
</Helmet>
<Child>
<Helmet>
<title>Nested Title</title>
<meta name="description" content="Nested component" />
</Helmet>
</Child>
</Parent>
react-helmet : https://jeonghwan-kim.github.io/dev/2020/08/15/react-helmet.html