🀍 은지log 🀍

[REACT] 반볡 ( Iteration ) 본문

πŸ’™ React

[REACT] 반볡 ( Iteration )

Eun_zii 2022. 10. 7. 17:43
  • λ°˜λ³΅μ„ 잘 μ‚¬μš©ν•˜λŠ”κ²Œ reactμ—μ„œ μ½”λ“œλ₯Ό μ€„μΌμˆ˜ μžˆλŠ” μ€‘μš”ν•œ 방법이닀.
  • reactμ—μ„œ λ°˜λ³΅μ„ μ‚¬μš©ν• λ•ŒλŠ” 배열을 μ΄μš©ν•œλ‹€.
  • map ν•¨μˆ˜λŠ” λ°°μ—΄μ—μ„œ μ‚¬μš©ν•˜λŠ” ν•¨μˆ˜μ΄κ³  μ‚¬μš©μ‹œ μƒˆλ‘œμš΄ ν•¨μˆ˜κ°€ λ°˜ν™˜λœλ‹€.
const number = [1,2,3,4,5]
const newNumbers = number.map(
(e) =>{
    console.log(e)
}) // (e)κ°€ 각각 μš”μ†Œκ°€ λ˜μ–΄ 1 2 3 4 5 κ°€ λ°˜ν™˜λœλ‹€.
---
const numbers = [1,2,3,4,5]
numbers.map( (number, i)=>{
  console.log(i)  
}) // 0 1 2 3 4
---
const numbers = [1,2,3,4,5]
const newNumbers = numbers.map((number, i) =>{
  return number*number;
}); // [1, 4, 9, 16, 25]

 

πŸ“ 배열을 μˆ˜μ •ν•΄μ„œ μƒˆλ‘œμš΄ 배열을 λ§Œλ“œλŠ”κ²Œ mapν•¨μˆ˜ 이고, κ·Έμ•ˆμ—λŠ” ν•¨μˆ˜κ°€ λ“€μ–΄κ°€μ„œ λ°°μ—΄μ˜ μ•ˆμ—μžˆλŠ” 원본 μš”μ†Œλ₯Ό μˆ˜μ •ν• μˆ˜ μžˆλ‹€.

const IterationSample = () => {
  const names = ['λˆˆμ‚¬λžŒ', 'μ–ΌμŒ', '눈', 'λ°”λžŒ']

  return (
    <ul>
      {names.map((name, i) => (
        <li key={i}>이름: {name}</li>
      ))}
    </ul>
  )
} 
export default IterationSample
  • mapν•¨μˆ˜λ‘œ 좜λ ₯ν• λ•ŒλŠ” mapν•¨μˆ˜ κ°€μž₯ λ°”κΉ₯μͺ½μ— key값을 λ„£μ–΄μ€˜μ•Όν•¨. key값은 mapν•¨μˆ˜ μ•ˆμ—μ„œ 항상 κ³ μœ ν•΄μ•Όν•¨. key값이 κ³ μœ ν•œ 값이 μ—†λ‹€λ©΄ i μ‚¬μš©.
  • 킀값이 ν•„μš”ν•œ μ΄μœ λŠ” λ¦¬μ•‘νŠΈκ°€ μž¬λžœλ”λ§μ„ ν• λ•Œ λ³€ν™”λœ λΆ€λΆ„λ§Œ λžœλ”λ§μ„ ν•˜λŠ”λ° 킀값을 보고 λžœλ”λ§μ„ 함. κ·Έλž˜μ„œ κ³ μœ ν•˜μ§€ μ•Šμ€ 킀값을 λ„£μœΌλ©΄ μ—λŸ¬λ°œμƒ.

 

1. input에 λ“€μ–΄κ°ˆ 값을 관리할 useStateλ³€μˆ˜ μ„ μ–Έ
2. input이 λ°”λ€”λ•Œλ§ˆλ‹€(onChange) setν•¨μˆ˜λ‘œ e.target.valueλ₯Ό useState λ³€μˆ˜μ— λ‹΄κΈ°
3. names 배열에 input에 λ‹΄κΈ΄ 값을 μΆ”κ°€

import { useState } from 'react'
const IterationSample = () => {
  const [names, setNames] = useState(['λˆˆμ‚¬λžŒ', 'μ–ΌμŒ', '눈', 'λ°”λžŒ'])
  const [text, setText] = useState('')
  const handleChange = (e) => {
    setText(e.target.value)
  }
  const handleClick = () => {
    if (!text) return
    const newNames = [...names, text]
    setNames(newNames)
    setText('')
  }
    return (
    <div>
      <input value={text} onChange={handleChange} />
      <button onClick={handleClick}>μΆ”κ°€</button>
      <ul>
        {names.map((name, i) => (
          <li key={i}>이름: {name}</li> // mapν•¨μˆ˜λ₯Ό μ¨μ„œ 좜λ ₯
        ))}
      </ul>
    </div>
  )
}
728x90

'πŸ’™ React' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

[REACT] Swiper μ‚¬μš©ν•˜μ—¬ ν„°μΉ˜μŠ¬λΌμ΄λ“œ κ΅¬ν˜„ν•˜κΈ°  (1) 2023.02.06
[REACT] 이벀트 ν•Έλ“€λŸ¬ ( Event handler )  (0) 2022.10.07
[REACT] HOOK  (0) 2022.10.07
[REACT] SCSS  (0) 2022.10.06
[REACT] SPA 와 async  (0) 2022.10.06