mangocoder
[React] Key 본문
반응형
SMALL
리액트에서 key는 컴포넌트 배열을 렌더링했을 때 어떤 원소에 변동이 있는지 알아내기위해 사용합니다. 예를 들어
유동적인 데이터를 다룰 때는 원소를 새로 생성할 수도, 제거할 수도, 수정할 수도 있습니다 key가 없을 때는 Virtual DOM을
비교하는 과정에서 리스트를 순차적으로 비교하면서 변화를 감지합니다. key가 있다면 변화를 조금 더 빠르게 알아낼 수 있습니다.
import React from "react";
const IterationSample = () => {
const names = ['눈사람' , '얼음' , '눈' , '바람'];
const nameList = names.map(name => <li>{name}</li>);
return <ul>{nameList}</ul>
}
export default IterationSample;
F12를 눌러서 콘솔(console)을 확인해보면 이러한 오류가 있을 겁니다. (”key”prop이 없다)
값에 index를 넣어서
import React from "react";
const IterationSample = () => {
const names = ['눈사람' , '얼음' , '눈' , '바람'];
const namesList = names.map((name,index) => <li key={index}>{name}</li>)
return <ul>{namesList}</ul>
};
export default IterationSample;
오류가 해결되었습니다
고유한 값이 없을 때만 index 값을 key로 사용해야합니다.
index를 key로 사용하면 배열이 변경될 때 효율적으로 리렌더링하지 못합니다.
import React , {useState} from "react";
const IterationSample = () => {
const [names , setNames] = useState([
{id : 1 , text : '눈사람'},
{id : 2 , text : '얼음'},
{id : 3 , text : '눈'},
{id : 4 , text : '바람'},
]);
const [inputText , setInputText] = useState('');
const [nextId , setNextId] = useState(5); //새로운 항목을 추가할 때 사용할 ID
const onChange = e => setInputText(e.target.value);
const onClick = () => {
const nextNames = names.concat({
id : nextId, //nextId 값을 id로 설정하고
text : inputText
});
setNextId(nextId + 1); // nextId 값에 1을 더해준다.
setNames(nextNames); //names 값을 업데이트한다.
setInputText(''); //inputText를 비운다.
};
const onRemove = id => { //삭제 기능
const nextNames = names.filter(name => name.id !== id);
setNames(nextNames);
};
const namesList = names.map(name => <li key={name.id} onDoubleClick={ () => onRemove(name.id)}>{name.text}</li>); //항목을 더블클릭시 삭제
return(
<>
<input value={inputText} onChange={onChange}/>
<button onClick={onClick}>추가</button>
<ul>{namesList}</ul>
</>
);
};
export default IterationSample;
반응형
LIST
'React(리액트)' 카테고리의 다른 글
[React] 스프링 연동 (1) | 2022.09.29 |
---|---|
[React] 버전5 → 버전6 바뀐 점 (2) | 2022.09.21 |
[React] JSX (0) | 2022.08.30 |
[React] 컴포넌트 (0) | 2022.08.29 |
[React] render , DOM (0) | 2022.08.29 |
Comments