리액트/컴포넌트반복

ch03.응용

webmaster 2021. 11. 10. 12:03
728x90

초기 상태 설정하기

  • 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);
      const namesList = names.map((name) => <li key={name.id}>{name.text}</li>);
      return <ul>{namesList}</ul>;
    };
    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);
    
      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(""); //inputText를 비운다
      };
      const namesList = names.map((name) => <li key={name.id}>{name.text}</li>);
      return (
        <>
          <input value={inputText} onChange={onChange} />
          <button onClick={onClick}>추가</button>
          <ul>{namesList}</ul>
        </>
      );
    };
    export default IterationSample;
  • 배열의 새항목을 추가할 때 push함수가 아닌 concat을 사용하였는데, push는 기존 배열 자체를 변경해 주는 반면, concat은 새로운 배열을 만들어 준다는 차이점이 있어 concat을 사용한 것이다.
  • 리액트에서는 상태를 업데이트할 때는 기존 상태를 그대로 두면서 새로운 값을 상태로 설정해야 한다(불변성 유지)
    • 이렇게 해야 리액트 컴포넌트의 성능을 최적화할 수 있다.

데이터 제거 기능 구현하기

  • 각 항목을 더블클릭 했을 때 해당 항목이 화면에서 사라지는 기능 구현
  • 불변성 유지하면서 업데이트를 해 주어야 한다.
    • filter를 사용하여 제거하면 불변성 유지가 가능하다.
    • const numbers = [1,2,3,4,5,6];
      const biggerThanThree = numbers.filter(number=>number>3);
      //4,5,6 리턴
      사용 예시(filter함수 인자에 분류하고 싶은 조건을 반환하는 함수를 넣어주면 쉽게 분류 가능하다.
    • const numbers = [1,2,3,4,5,6];
      const withoutThree = numbers.filter(number=>number !== 3);
      //1,2,4,5,6 리턴
  • 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);
    
      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(""); //inputText를 비운다
      };
      const onRemove = (id) => {
        const nextNames = names.filter((name) => name.id !== id);
        setNames(nextNames);
      };
      const namesList = names.map((name) => (
        <li key={name.id} onDoubleClick={() => onRemove(name.id)}>
          {name.text}
        </li>
      ));
      return (
        <>
          <input value={inputText} onChange={onChange} />
          <button onClick={onClick}>추가</button>
          <ul>{namesList}</ul>
        </>
      );
    };
    export default IterationSample;

 

728x90

'리액트 > 컴포넌트반복' 카테고리의 다른 글

ch02.Key  (0) 2021.11.10
ch01.자바스크립트 배열의 map() 함수  (0) 2021.11.10