컴포넌트 반복

이종현·2020년 9월 15일
0

React

목록 보기
6/12

문법

arr.map(callback, [thisArg])

이 함수의 파라미터는 다음과 같습니다.

1)callback: 새로운 배열의 요소를 생성하는 함수로 파라미터는 다음 세가지 입니다.
1-1 currentValue: 현재 처리하고 있는 요소
1-2 index: 현재 처리하고 있는 요소의 index
1-3 array: 현재 처리하고 있는 원본 배열

2)thisArg(선택항목):callback 함수 내부에서 사용할 this 레퍼런스

key

리액트에서 key는 컴포넌트 배열을 렌더링햇을 때 어떤 원소에 변동이 있었는지 알아내려고 사용합니다.

key 설정

key값을 설정할 때는 map 함수의 인자로 전달되는 함수 내부에서 컴포넌트 props를 설정하듯이 설정하면 됩니다. key값은 언제나 유일해야 합니다. 따라서 데이터가 가진 고윳값을 key 값으로 설정해야 합니다.

import React from "react";

const IterationSample = () => {
  const names = ["눈사람", "얼음", "눈", "바람"];
  const nameList = names.map((name, index) => <li key={index}>{name}</li>);
  return (
    <div>
      <ul>{nameList}</ul>
    </div>
  );
};

export default IterationSample;

데이터 추가 기능 구현하기

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(""); //inputTextf 초기화
  };

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

  return (
    <div>
      <input value={inputText} onChange={onChange} />
      <button onClick={onClick}>추가</button>
      <ul>{nameList}</ul>
    </div>
  );
};

export default IterationSample;

배열에 새 항목을 추가할 때 배열의 push 함수를 사용하지 않고 concat을 사용했는데요, push 함수는 기존 배열 자체를 변경해 주는 반면, concat은 새로운 배열을 만들어 준다는 차이점이 있습니다.
리액에서 상태를 업데이트할 때는 기존 상태를 그대로 두면서 새로운 값을 상태로 설정해야 합니다. 이를 불변성 유지라고 하는데요, 불면성 유지를 해 주어야 나중에 리액트 컴포넌트의 성능을 최적화할 수 있습니다.

데이터 제거 기능 구현하기

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(""); //inputTextf 초기화
  };

  const onRemove = (id) => {
    const nextNames = names.filter((name) => name.id !== id);
    setNames(nextNames);
  };

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

  return (
    <div>
      <input value={inputText} onChange={onChange} />
      <button onClick={onClick}>추가</button>
      <ul>{nameList}</ul>
    </div>
  );
};

export default IterationSample;
profile
꿈 을 코딩하자

0개의 댓글