기존 코드
import { sculptureList } from './data.js';
export default function Gallery() {
let index = 0;
function handleClick() {
index = index + 1;
}
let sculpture = sculptureList[index];
return (
<>
<button onClick={handleClick}>
Next
</button>
<h2>
<i>{sculpture.name} </i>
by {sculpture.artist}
</h2>
<h3>
({index + 1} of {sculptureList.length})
</h3>
<img
src={sculpture.url}
alt={sculpture.alt}
/>
<p>
{sculpture.description}
</p>
</>
);
}
import { useState } from 'react';
// 기존 코드
let index = 0;
// 변경 코드
const [index, setIndex] = useState(0);
function handleClick() {
setIndex(index + 1);
}
const [index, setIndex] = useState(0);
useState(0)은 [0, setIndex]를 반환하며, 0을 최신 state 값으로 기억한다.setIndex(index + 1)을 호출하며, React는 index를 1로 기억한 상태로 다른 렌더링을 유발한다.useState(0)을 보지만 index가 1로 기억되므로 [1, setIndex]를 반환한다.setArtists( // 아래의 새로운 배열로 state를 변경합니다.
[
...artists, // 기존 배열의 모든 항목에,
{ id: nextId++, name: name } // 마지막에 새 항목을 추가합니다.
]
);
setArtists(
artists.filter(a => a.id !== artist.id)
);
function handleClick() {
const nextShapes = shapes.map(shape => {
if (shape.type === 'square') {
// 변경시키지 않고 반환합니다.
return shape;
} else {
// 50px 아래로 이동한 새로운 원을 반환합니다.
return {
...shape,
y: shape.y + 50,
};
}
});
// 새로운 배열로 리렌더링합니다.
setShapes(nextShapes);
}
function handleClick() {
const insertAt = 1; // 모든 인덱스가 될 수 있습니다.
const nextArtists = [
// 삽입 지점 이전 항목
...artists.slice(0, insertAt),
// 새 항목
{ id: nextId++, name: name },
// 삽입 지점 이후 항목
...artists.slice(insertAt)
];
setArtists(nextArtists);
setName('');
}