2020. 2. 12. 17:13

자바스크립트 map ( ) 함수

  • 리액트 프로젝트에서 반복적인 컴포넌트를 렌더링할 때 "map 함수"를 사용
  • map( ) 함수는 파라미터로 전달된 함수를 사용해서 배열 내 각 요소를 원하는 규칙에 따라 변환한 후 그 결과로 새로운 배열 생성
  • 문법 : array.map( callback( currentValue, index, array), [thisArg] )
    • callback 함수 : 새로운 배열의 요소를 생성하는 함수 
      • currentValue : 현재 처리하고 있는 요소
      • index : 현재 처리하고 있는 요소의 index 값
      • array : 현재 처리하고 있는 원본 배열
    • thisArg (선택항목) : callback 함수 내부에서 사용할 this 레퍼런스
  • key : 컴포넌트 배열을 렌더링했을 때 어떤 원소에 변동이 있었는지 알아내기 위해 사용
    • key 값 설정시 map 함수의 인자로 전달되는 함수 내부에서 컴포넌트 props를 설정하듯이 설정
    • key값은 유일해야 함

 

동적 배열 렌더링 - 초기 상태 설정

import React, { useState } from 'react';

const DynamicArray = () => {
  const [names, setNames] = useState([
    { id: 1, text: 'kim' },
    { id: 2, text: 'lee' },
    { id: 3, text: 'park' }
  ]);
//   const [inputText, setInputText] = useState('');
//   const [nextId, setNextId] = useState(4);

  const nameList = names.map(name => <li key={name.id}>{name.text}</li>);

  return (
    <>
      <ul>{nameList}</ul>
    </>
  );
};

export default DynamicArray;

 

동적 배열 렌더링 - 데이터 추가 기능 : 배열의 concat 메소드 활용

- concat 은 두 개의 문자열을 하나의 문자열로 만들어주는 역활을 하는 함수이며,

   입력값을 문자열 대신 배열을 사용하면 두 개의 배열을 하나의 배열로 만들어주는 역활도 하는 함

import React, { useState } from 'react';

const DynamicArray = () => {
  const [names, setNames] = useState([
    { id: 1, text: 'kim' },
    { id: 2, text: 'lee' },
    { id: 3, text: 'park' }
  ]);
  const [inputText, setInputText] = useState('default text');
  const [nextId, setNextId] = useState(4);

  const handleChange = e => {
    setInputText(e.target.value);
  };

  const handleClick = () => {
    const nextNames = names.concat({
      id: nextId,
      text: inputText
    });
    setNames(nextNames);
    setNextId(nextId + 1);
    setInputText('');
  };

  const nameList = names.map(name => <li key={name.id}>{name.text}</li>);

  return (
    <>
      <input value={inputText} onChange={handleChange}></input>
      <button onClick={handleClick}>add</button>
      <ul>{nameList}</ul>
    </>
  );
};

export default DynamicArray;

 

동적 배열 렌더링 - 데이터 삭제 기능 : 배열의 filter 메소드 활용

- filter 함수 : 지정된 조건에 맞는 요소들로 이루어진 새로운 배열 반환하는 함수

import React, { useState } from 'react';

const DynamicArray = () => {
  const [names, setNames] = useState([
    { id: 1, text: 'kim' },
    { id: 2, text: 'lee' },
    { id: 3, text: 'park' }
  ]);
  const [inputText, setInputText] = useState('default text');
  const [nextId, setNextId] = useState(4);

  const handleChange = e => {
    setInputText(e.target.value);
  };

  const handleClick = () => {
    const nextNames = names.concat({
      id: nextId,
      text: inputText
    });
    setNames(nextNames);
    setNextId(nextId + 1);
    setInputText('');
  };

  const handleRemove = id => {
    const filteredNames = names.filter(name => name.id != id);
    setNames(filteredNames);
  };

  const nameList = names.map(name => (
    <li key={name.id} onDoubleClick={() => handleRemove(name.id)}>
      {name.text}
    </li>
  ));

  return (
    <>
      <input value={inputText} onChange={handleChange}></input>
      <button onClick={handleClick}>add</button>
      <ul>{nameList}</ul>
    </>
  );
};

export default DynamicArray;

 

 

'Javascript > React' 카테고리의 다른 글

#6 React Hooks  (0) 2020.02.14
#5 React Component Lifecycle  (0) 2020.02.13
#3 React Event Handling  (0) 2020.02.12
#2 React Component  (0) 2020.02.12
#1 basic react  (0) 2020.02.12
Posted by yongminLEE