const IterSample = () => {
	return(
    	<ul>
    		<li>...</li>
        	...
    	</ul>
    );

1. 자바스크립트 배열의 MAP 함수 이용하기

  • 파라미터로 전달된 함수를 사용하여 배열 내 각 요소를 원하는 규칙에 따라 변환 후 그 결과로 새로운 배열 생성
arr.map(callback, [thisArg])
  • callback : 새로운 배열의 요소를 생성하는 함수, 파라미터는 3개
    -currentValue : 현재 처리하고 있는 요소
    -index : 현재 처리하고 있는 요소의 index
    -array : 현재 처리하고 있는 원본 배열
  • thisArg(선택항목) : callback함수 내부에서 사용할 this 레퍼런스
const name = [1,2,3,4,5]

const result = name.map(num=>num*num);
  • 화살표 함수 사용 시 return값 하나만 존재한다면 중괄호안에 넣을 필요 없음

2. 데이터 배열을 컴포넌트 배열로 반환

const IterSample = () => {
	const name = [1,2,3,4,5]
    const result = name.map(name=><li>{name}</li>);
	return(
    	<ul>
    		{result}
    	</ul>
    );

3. key

  • 컴포넌트 배열 렌더링 시, 어떤 원소에 변동이 있는지 알아내기 위해서 사용
  • 인자로 전달되는 함수 내부에서 props 설정하듯이 하면 됨.

const result = name.map((name,index)=><li key={index}>{name}</li>);
  • index를 key로 사용 시, 비효율적인 리렌더링이 됨
import React, { useState } from "react";

const IterSample = () => {
  const [names, setNames] = useState([
    { id: 1, text: "a" },
    { id: 2, text: "b" },
    { id: 3, text: "c" }
  ]);

  const [inputText, setInputText] = useState("");
  const [nextId, setNextId] = useState(5);
  const result = names.map((name) => <li key={name.id}>{name.text}</li>);
  const onChange = (e) => setInputText(e.target.value);

  return (
    <>
      <ul>{result}</ul>
      <input onChange={onChange} value={inputText} />
      <button>click</button>
    </>
  );
};

export default IterSample;

useState : []형태를 반환하기 때문에 객체가 아닌 배열로 만들어서 받아줘야함.

  • map 함수에서는 전체 names 객체를 하나씩 받아오기 때문에 id, text부분을 나눠서 보여줌
  • input의 Text를 받아오기 위해서 value값을 state로 설정 후 setter 함수로 값을 변경함.

3.1. 데이터 추가하기

import React, { useState } from "react";

const IterSample = () => {
  const [names, setNames] = useState([
    { id: 1, text: "a" },
    { id: 2, text: "b" },
    { id: 3, text: "c" }
  ]);

  const [inputText, setInputText] = useState("");
  const [nextId, setNextId] = useState(5);
  const result = names.map((name) => <li key={name.id}>{name.text}</li>);
  const onChange = (e) => setInputText(e.target.value);
  const onClick = () => {
    const newName = names.concat({
      id: nextId,
      text: inputText
    });
    setNextId(nextId + 1);
    setNames(newName);
    setInputText("");
  };
  return (
    <>
      <ul>{result}</ul>
      <input onChange={onChange} value={inputText} />
      <button onClick={onClick}>click</button>
    </>
  );
};

export default IterSample;
  • onClick 함수 추가 : 화면에 input에 친 내용이 그대로 노출됨
  • setNames를 통해 names값을 업데이트함.
  • concat : 새로운 배열을 만들어줌.

3.2. 데이터 삭제하기

  • filter 함수 사용 : 조건을 만족하는 원소들만 반환
const a = [1,2,3,4,5,6];
const b = a.filter(n=>n>3); // [4,5,6] 
const c = a.filter(n=>n!==3);// [1,2,4,5,6] 
import React, { useState } from "react";

const IterSample = () => {
  const [names, setNames] = useState([
    { id: 1, text: "a" },
    { id: 2, text: "b" },
    { id: 3, text: "c" }
  ]);

  const [inputText, setInputText] = useState("");
  const [nextId, setNextId] = useState(5);
  const result = names.map((name) => <li key={name.id} onDoubleClick={()=>{onRemove(name.id)}}>{name.text}</li>);

  const onChange = (e) => setInputText(e.target.value);

  const onClick = () => {
    const newName = names.concat({
      id: nextId,
      text: inputText
    });
    setNextId(nextId + 1);
    setNames(newName);
    setInputText("");
  };

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

  return (
    <>
      <ul>{result}</ul>
      <input onChange={onChange} value={inputText} />
      <button onClick={onClick}>click</button>
    </>
  );
};

export default IterSample;
  • onDoubleClick 이벤트를 활용하여 더블클릭한 text 삭제되도록 함
  • 배열 자체를 수정하는 것이 아닌 새로운 배열로 만들어서 덮어씌워줘야함.
profile
hello world!

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN