상수 데이터?
- 변하지 않는 데이터, 즉 정적인 데이터
✔️ 상수 데이터를 사용하는 이유
- 반복되는 UI 를 하드코딩으로 하나하나 만들어두게 되면, 코드가 길어져 가독성이 좋지 않고, 수정이 필요할 때 해당하는 부분을 찾기 힘들어 추후 유지보수가 힘들어질 수 있다
이러한 반복되는 UI 를 상속 데이터 + array.map() 함수의 조합을 이용해 간결하게 표현 가능
추후에 수정할 필요가 생겼을 경우, 상수 데이터에서 해당하는 부분의 내용만 변경해주면 되기 때문에 유지보수가 용이
import React from "react";
import Comment from "./Comment/Comment";
import "./CommentList.scss";
function CommentList() {
return (
<div className="commentList">
<h1>댓글</h1>
<ul>
<Comment
name="wecode"
comment="Welcome to world best coding bootcamp"
isLiked={true}
/>
<Comment
name="joonsikyang"
comment="Hi therer."
isLiked={false}
/>
<Comment
name="jayPark"
comment="Hey."
isLiked={false}
/>
</ul>
</div>
);
}
export default CommentList;
☑️ commentData.js
const COMMENT_LIST = [
{
id: 1,
userName: 'wecode',
content: 'Welcome to world best coding bootcamp!',
isLiked: true
},
{
id: 2,
userName: 'joonsikyang',
content: 'Hi there.',
isLiked: false
},
{
id: 3,
userName: 'jayPark',
content: 'Hey.',
isLiked: false
}
];
export default COMMENT_LIST;
☑️ CommentList.js
import React from 'react';
import Comment from './Comment/Comment';
import COMMENT_LIST from './commentData';
import './CommentList.scss';
function CommentList() {
return (
<div className="commentList">
<h1>댓글</h1>
<ul>
{COMMENT_LIST.map(comment => {
return (
<Comment
key={comment.id}
name={comment.userName}
comment={comment.content}
/>
);
})}
</ul>
</div>
);
}
export default CommentList;
‼️ 이 때, 해당 파일에서만 사용하는 간단한 상수 데이터의 경우 파일 내부에 선언해서 사용하기도 한다.
( 상수 데이터의 길이가 너무 길거나, 여러 개의 파일에서 공통적으로 사용하는 경우에는 위의 경우처럼 별도의 JS파일로 분리해서 사용한다.)
-CommentList.js
✔️ 해당 파일에서 가장 중요한 내용은 컴포넌트 이기 때문에, 중요도의 순서에 따라 컴포넌트 다음에 상수 데이터를 선언해주어야 한다.
import React from 'react';
import Comment from './Comment/Comment';
import './CommentList.scss';
function CommentList() {
return (
<div className="commentList">
<h1>댓글</h1>
<ul>
{COMMENT_LIST.map(comment => {
return (
<Comment
key={comment.id}
name={comment.userName}
comment={comment.content}
/>
);
})}
</ul>
</div>
);
}
const COMMENT_LIST = [
{
id: 1,
userName: 'wecode',
content: 'Welcome to world best coding bootcamp!',
isLiked: true
},
{
id: 2,
userName: 'joonsikyang',
content: 'Hi there.',
isLiked: false
},
{
id: 3,
userName: 'jayPark',
content: 'Hey.',
isLiked: false
}
];
export default CommentList;
파란색 박스로 표시되어 있는 Footer 에 들어가는 값처럼 반복된 UI 이면서, 변하지 않는 값들 같은 경우, 상수 데이터로 만들어서 렌더링하면 훨씬 간편하고, 유지보수에 용이