π https://react.dev/learn/state-a-components-memory
μΉνμ΄μ§μμ μνΈμμ©μΌλ‘ νλ©΄μ λ΄μ©μ λ³κ²½ν΄μΌ νλ κ²½μ°
μμ μ
λ ₯νλ©΄ μ
λ ₯ νλκ° μ
λ°μ΄νΈ λκ±°λ, 'λ€μ'λ²νΌμ λλ₯΄λ©΄ νμλλ λ΄μ©μ΄ λ³κ²½λκ±°λ, 'ꡬ맀'λ²νΌμ ν΄λ¦νλ©΄ μ₯λ°κ΅¬λμ λ΄κΈ°κ² λλ λ±
μ»΄ν¬λνΈλ νμ¬μ μ
λ ₯ κ°, λ΄μ©, μ₯λ°κ΅¬λ λ±μ κΈ°μ΅ν΄μΌ νλ€!
Reactμμλ μ΄λ¬ν μ’
λ₯μ ꡬμ±μμλ³ λ©λͺ¨λ¦¬λ₯Ό state λΌ λΆλ₯Έλ€.
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>
</>
);
}
μ½λμμ handleClick() μ΄λ²€νΈ νΈλ€λ¬λ indexλΌλ μ§μ λ³μλ₯Ό λ³κ²½νλ ν¨μμ΄λ€.
λ€λ§ μ μ½λλ‘ μμ±λ νμ΄μ§μμλ indexμ λ³νλ₯Ό λ°λ‘ νμΈν μ μλ€.
μ¦ Next λ²νΌμ λλ¬ μ΄λ²€νΈ νΈλ€λ¬κ° μλλμ΄λ λ·°νμ΄μ§μμλ μλ¬΄λ° λ³νκ° μΌμ΄λμ§ μλλ€.
μ΄λ μ§μλ³μκ° λ€μ λ κ°μ§ νΉμ±μ κ°κΈ° λλ¬Έμ΄λ€.
// κ° λ³μμ νΉμ κ° μ μ₯νλ λ°©λ²
// 1. λ°°μ΄μ λ£κ³ μΈλ±μ€λ‘ μ κ·Όν΄ μ μ₯
let num = [1,2];
let a = num[0];
let b = num[1];
// a == 1 , b == 2
// 2. Destructuring
let [c,d] = [1,2];
// c == 1 , d == 2
useStateλ const [ something, setSomething ] = useState(λ³μ μ΄κΈ°κ°); μ νμμΌλ‘ μ¬μ©λλ©°, useStateλ [something κ°, setSomething(ν¨μ)]μ λ°ννλ€.
something: state λ³μ, λ λ λ μ¬μ΄μ λ°μ΄ν°λ₯Ό μ μ§ν΄μ€λ€.setSomething : λ³μλ₯Ό μ
λ°μ΄νΈνκ³ Reactλ₯Ό νΈλ¦¬κ±°ν΄ κ΅¬μ± μμλ₯Ό λ€μ λ λλ§νκ² ν΄μ£Όλ state μ€μ ν¨μ(state setter function)μ΄λ€.μ°Έκ³ )
ν΅μμ μΌλ‘ const [ something, setSomething ] νμμΌλ‘ λ³μλͺ
μ μμ±νλ€.
λ§μλλ‘ μμ±ν μ μμ§λ§, 컨벀μ
μ λ°λ₯΄λ©΄ μ½λλ₯Ό μ΄ν΄ν λ λμμ΄ λ κ²!
μμμ μμ±ν μ½λμ stateλ₯Ό μ μ©νμ¬ κ°μ΄ λ³κ²½λ λλ§λ€ νμ΄μ§κ° λ λλμ΄ λ³κ²½ κ°μ νμΈν μ μλλ‘ μμ ν΄λ³΄μ.
import { sculptureList } from './data.js';
import { useState } from 'react'; // useState import
export default function Gallery() {
// let index = 0;
const [index, setIndex] = useState(0); //useState μ¬μ©
function handleClick() {
// index = index + 1;
setIndex(index + 1);
}
const [index, setIndex] = useState(0);
indexκ° state λ³μ, setIndexκ° state setter functionμ΄λ€.
const [index, setIndex] = useState(0);
μ μμ μ½λλ₯Ό ν΅ν΄ λμ κ³Όμ μ νμΈν΄λ³΄μ.
1. κ΅¬μ± μμκ° μ²μμΌλ‘ λ λλλ€
useStateμ μ΄κΈ°κ°μΌλ‘ 0μ indexμ μ λ¬νκΈ° λλ¬Έμ useStateλ [0, setIndex]μ λ°ννλ€.
Reactλ state λ³μμ μ΅μ κ°μΈ 0μ κΈ°μ΅νλ€.
2. stateκ° μ
λ°μ΄νΈλλ€
μ μ κ° λ²νΌμ ν΄λ¦νλ©΄, νΈλ€λ¬ ν¨μκ° setIndex(index+1)μ νΈμΆνλ€. indxeκ° 0μ΄κΈ° λλ¬Έμ, setIndex(1)μ΄ μ μ©λμ΄ index κ°μ΄ 1λ‘ λ³κ²½λλ€.
μ΄λ Reactκ° index κ°μ 1λ‘ κΈ°μ΅νκ² λ§λ€κ³ λ λλ₯Ό νΈλ¦¬κ±°νλ€.
3. λ λ²μ§Έ λ λκ° μ§νλλ€
Reactλ [1, setIndex]λ₯Ό λ°ννλ€.